模拟post请求

来源:互联网 发布:西安交通大学网络导航 编辑:程序博客网 时间:2024/06/01 09:13

  1. #region  向Url发送post请求  
  2. /// <summary>  
  3. /// 向Url发送post请求  
  4. /// </summary>  
  5. /// <param name="postData">发送数据</param>  
  6. /// <param name="uriStr">接受数据的Url</param>  
  7. /// <returns>返回网站响应请求的回复</returns>  
  8. public static string RequestPost(string postData, string uriStr)  
  9. {  
  10.     HttpWebRequest requestScore = (HttpWebRequest)WebRequest.Create(uriStr);  
  11.   
  12.     ASCIIEncoding encoding = new ASCIIEncoding();  
  13.     byte[] data = encoding.GetBytes(postData);  
  14.     requestScore.Method = "Post";  
  15.     requestScore.ContentType = "application/x-www-form-urlencoded";  
  16.     requestScore.ContentLength = data.Length;  
  17.     requestScore.KeepAlive = true;  
  18.   
  19.     Stream stream = requestScore.GetRequestStream();  
  20.     stream.Write(data, 0, data.Length);  
  21.     stream.Close();  
  22.   
  23.     HttpWebResponse responseSorce;  
  24.     try  
  25.     {  
  26.         responseSorce = (HttpWebResponse)requestScore.GetResponse();  
  27.     }  
  28.     catch (WebException ex)  
  29.     {  
  30.         responseSorce = (HttpWebResponse)ex.Response;//得到请求网站的详细错误提示  
  31.     }  
  32.     StreamReader reader = new StreamReader(responseSorce.GetResponseStream(), Encoding.UTF8);  
  33.     string content = reader.ReadToEnd();  
  34.   
  35.     requestScore.Abort();  
  36.     responseSorce.Close();  
  37.     responseSorce.Close();  
  38.     reader.Dispose();  
  39.     stream.Dispose();  
  40.     return content;  
  41. }  
  42. #endregion  

网站得到Post过来的数据:

  1. /// <summary>  
  2. /// 得到程序post过来的数据  
  3. /// </summary>  
  4. /// <returns></returns>  
  5. private string GetPostContent()  
  6. {  
  7.     string postStr = string.Empty;  
  8.     Stream inputStream = Request.InputStream;  
  9.     int contentLength = Request.ContentLength;  
  10.     int offset = 0;  
  11.     if (contentLength > 0)  
  12.     {  
  13.         byte[] buffer = new byte[contentLength];  
  14.         for (int i = inputStream.Read(buffer, offset, contentLength - offset); i > 0; i = inputStream.Read(buffer, offset, contentLength - offset))  
  15.         {  
  16.             offset += i;  
  17.         }  
  18.         UTF8Encoding encoding = new UTF8Encoding();  
  19.         postStr = encoding.GetString(buffer);  
  20.     }  
  21.     return postStr;  
  22. }  

0 0
原创粉丝点击