C#调用外部接口(POST、GET)

  • C#调用外部接口(POST、GET)已关闭评论
  • 196 次浏览
  • A+
所属分类:.NET技术
摘要

 public string HttpPost() {//把用户传过来的数据转成“UTF-8”的字节流
Encoding encoding = Encoding.UTF8;
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(“http://接口IP地址:端口号/接口路径”);     //比如:http://192.168.123.12:8080/api/post


在C#中调用StringBoot接口,POST请求,案例代码:

 

public string HttpPost(

{

//把用户传过来的数据转成“UTF-8”的字节流
Encoding encoding = Encoding.UTF8;
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://接口IP地址:端口号/接口路径");     //比如:http://192.168.123.12:8080/api/post

 

//调用POST方法
request.Method = "POST";
request.ContentType = "application/json; charset=UTF-8";
request.Headers["Accept-Encoding"] = "gzip, deflate";

 

//content为body中的参数
String content = "{"message":"请求成功"," +
""nid":"0000001"," +
""details":"员工"," +
""name":"zhangsan"}";

 

byte[] buffer = encoding.GetBytes(content);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);

 

//通过Web访问对象获取响应内容
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//通过响应内容流创建StreamReader对象
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
//利用StreamReader就可以从响应内容从头读到尾,结果是String类型
var retString = reader.ReadToEnd();

 }

 

return retString; 结果是一个字符串类型:

 

GET请求,案例代码:

 

public string HttpGet()
{

//把用户传过来的数据转成“UTF-8”的字节流
Encoding encoding = Encoding.UTF8;
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("接口地址");

 

//调用GET方法
request.Method = "GET";
request.ContentType = "application/json";
request.Headers["Accept-Encoding"] = "gzip,deflase";

request.AutomaticDecompression = DecompressionMethods.GZip;
//通过Web访问对象获取响应内容
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

 

// HttpCookie cookies = new HttpCookie("admin");  //如果有需要通过登录实现保存cookie值的话可以加一部分
// cookies.Value = Convert.ToString(response.Headers["Set-Cookie"]); // 通过响应请求读取带cookie的http数据
// cookies.Expires = DateTime.Now.AddDays(1);
//  HttpContext.Current.Response.Cookies.Add(cookies);

 

//通过响应内容流创建StreamReader对象
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)
//利用StreamReader从响应内容从头读到尾
return reader.ReadToEnd();

}