今天總結一下,調用第三方介面地址,以POST方式進行HTTP請求,並且入參為JSON格式方法: 引用:using System.Text;using System.Net;using System.IO; string url="http://";//第三方介面地址 paramStr //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;