首页 电脑 电脑学堂 查看内容

实现http的post和get的几种方法

2014-12-30 11:19 1271 0

摘要: 1.POST方法(httpWebRequest)POST方法(httpWebRequest)[csharp] view plaincopy#region  POST方法(...
关键词: nbsp httpWebRequest string plaincopy HttpWebResponse Encoding csharp StreamReader view POST

1.POST方法(httpWebRequest)POST方法(httpWebRequest)[csharp] view plaincopy#region  POST方法(httpWebRequest)    //body是要传递的参数,格式"roleId=1&uid=2"  //post的cotentType填写:  //"application/x-www-form-urlencoded"  //soap填写:"text/xml; charset=utf-8"      public static string PostHttp(string url, string body, string contentType)      {          HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);            httpWebRequest.ContentType = contentType;          httpWebRequest.Method = "POST";          httpWebRequest.Timeout = 20000;            byte[] btBodys = Encoding.UTF8.GetBytes(body);          httpWebRequest.ContentLength = btBodys.Length;          httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();          StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());          string responseContent = streamReader.ReadToEnd();            httpWebResponse.Close();          streamReader.Close();          httpWebRequest.Abort();          httpWebResponse.Close();            return responseContent;      }  #endregion  [csharp] view plaincopy  [csharp] view plaincopy</pre></p><p><span style="font-size:18px;color:#ff0000;">2.POST方法(WebClient)</span></p><p><pre class="csharp" name="code">/// <summary>          /// 通过WebClient类Post数据到远程地址,需要Basic认证;          /// 调用端自己处理异常          /// </summary>          /// <param name="uri"></param>          /// <param name="paramStr">name=张三&age=20</param>          /// <param name="encoding">请先确认目标网页的编码方式</param>          /// <param name="username"></param>          /// <param name="password"></param>          /// <returns></returns>          public static string Request_WebClient(string uri, string paramStr, Encoding encoding, string username, string password)          {              if (encoding == null)                  encoding = Encoding.UTF8;  [csharp] view plaincopy            string result = string.Empty;  [csharp] view plaincopy            WebClient wc = new WebClient();  [csharp] view plaincopy            // 采取POST方式必须加的Header              wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");  [csharp] view plaincopy            byte[] postData = encoding.GetBytes(paramStr);  [csharp] view plaincopy
    声明:文章版权归原作者所有 部分文章转自互联网 如有侵权请联系 [邮箱地址] 删除

    路过

    雷人

    握手

    鲜花

    鸡蛋

    最新评论

    返回顶部