以POST方式进行HTTP请求调用(入参为JSON格式)
今天总结一下,调用第三方接口地址,以POST方式进行HTTP请求,并且入参为JSON格式方法:
引用:using System.Text;using System.Net;using System.IO;
string url="http://";//第三方接口地址
paramStr //json字符串 入参
Encoding encoding = Encoding.UTF8;
调用:HttpResult result=GetHttpNewWeb(url, paramStr, encoding)
public HttpResult GetHttpNewWeb(string url, string paramStr, Encoding encoding) { HttpResult r = new HttpResult(); string responseString = string.Empty; HttpWebRequest myRequest =null; HttpWebResponse myResponse = null; try { //JObject jobj = new JObject(new JProperty("json", paramStr)); byte[] data =Encoding.UTF8.GetBytes(paramStr); myRequest = HttpWebRequest.Create(url) as HttpWebRequest;// 注意,这里不能写 myRequest = (HttpWebRequest)WebRequest.Create(url); DateTime start_time = DateTime.Now; myRequest.Timeout = 60000; myRequest.Method = "POST"; myRequest.ContentType = "application/json"; using (Stream stream = myRequest.GetRequestStream()) { stream.Write(data, 0, data.Length); } HttpWebResponse EhealthResp = myRequest.GetResponse() as HttpWebResponse; Stream EhealthResu = EhealthResp.GetResponseStream(); StreamReader EhealthSr = new StreamReader(EhealthResu, Encoding.GetEncoding("UTF-8")); string finalStr = EhealthSr.ReadToEnd(); r.result = true; r.html = finalStr; return r; } catch (Exception ex) { r.html = ex.ToString(); if (myRequest != null) myRequest.Abort(); if (myResponse != null) myResponse.Close(); return r; } r.html = "调用完成,URL地址" + url; r.result = false; return r; }
string fanhuizhi = result.html;