欢迎光临
我的个人博客网站

以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;

赞(0) 打赏
未经允许不得转载:张拓的天空 » 以POST方式进行HTTP请求调用(入参为JSON格式)
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

专业的IT技术经验分享 更专业 更方便

联系我们本站主机

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏