c# http Post Get 方法
/// <summary>
/// get方式访问webapi
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string httpGet(string url)
{
try
{
HttpWebRequest MyRequest = (HttpWebRequest)WebRequest.Create(url);
MyRequest.Method = "GET";
MyRequest.Accept = "application/json";
//返回类型可以为
//1、application/json
//2、text/json
//3、application/xml
//4、text/xml
MyRequest.ContentType = "application/json";
//上传类型是能为json
string retData = null;//接收返回值
HttpWebResponse MyResponse = (HttpWebResponse)MyRequest.GetResponse();
if (MyResponse.StatusCode == HttpStatusCode.OK)
{
Stream MyNewStream = MyResponse.GetResponseStream();
StreamReader MyStreamReader = new StreamReader(MyNewStream, Encoding.UTF8);
retData = MyStreamReader.ReadToEnd();
MyStreamReader.Close();
}
MyResponse.Close();
return retData;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// post方式访问webapi
/// </summary>
/// <param name="url"></param>
/// <param name="postdata"></param>
/// <returns></returns>
public static string httpPost(string url, string postdata)
{
try
{
HttpWebRequest MyRequest = (HttpWebRequest)WebRequest.Create(url);
MyRequest.Method = "POST";
MyRequest.Accept = "application/json";
//返回类型可以为
//1、application/json
//2、text/json
//3、application/xml
//4、text/xml
MyRequest.ContentType = "application/json";
//上传类型是能为json
if (postdata != null)
{
ASCIIEncoding MyEncoding = new ASCIIEncoding();
byte[] MyByte = MyEncoding.GetBytes(postdata);
Stream MyStream = MyRequest.GetRequestStream();
MyStream.Write(MyByte, 0, postdata.Length);
MyStream.Close();
}
string retData = null;//返回值
HttpWebResponse MyResponse = (HttpWebResponse)MyRequest.GetResponse();
if (MyResponse.StatusCode == HttpStatusCode.OK)
{
Stream MyNewStream = MyResponse.GetResponseStream();
StreamReader MyStreamReader = new StreamReader(MyNewStream, Encoding.UTF8);
retData = MyStreamReader.ReadToEnd();
MyStreamReader.Close();
}
MyResponse.Close();
return retData;
}
catch (Exception ex)
{
return ex.Message;
}
}
最新文章
- Java开源库
- spark - tasks is bigger than spark.driver.maxResultSize
- wordpress钩子和钩子函数
- jquery 清空 iframe 的内容,,iframe自适应高度
- 移动端事件touchstart、touchmove、touchend
- 在ubuntu上搭建开发环境7---ubuntu安装JDK
- 【代码分享】简单html5足球射门游戏分享
- oracle时间格式转换问题 ORA-01810: format code appears twice--转
- php mysql 数据库写入与读取取文件
- 自己定义View----点击滑动选择字母列表
- .NET 跨平台界面框架和为什么你首先要考虑再三
- window.showModalDialog
- springcloud~服务注册与发现Eureka的使用
- 如何用浏览器在线查看.ipynb文件
- Oracle中对XMLType的简单操作(extract、extractvalue...)
- Spring IoC和AOP使用扩展
- webservice:com.sun.xml.internal.ws.server.ServerRtException: [failed to localize]
- 处理:&ldquo;ORA-00257: archiver error. Connect internal only, until freed&rdquo;的错误问题
- java将所有的字符串转换为大写或小写
- P1044-栈-洛谷luogu