- #region 向Url发送post请求
- /// <summary>
- /// 向Url发送post请求
- /// </summary>
- /// <param name="postData">发送数据</param>
- /// <param name="uriStr">接受数据的Url</param>
- /// <returns>返回网站响应请求的回复</returns>
- public static string RequestPost(string postData, string uriStr)
- {
- HttpWebRequest requestScore = (HttpWebRequest)WebRequest.Create(uriStr);
- ASCIIEncoding encoding = new ASCIIEncoding();
- byte[] data = encoding.GetBytes(postData);
- requestScore.Method = "Post";
- requestScore.ContentType = "application/x-www-form-urlencoded";
- requestScore.ContentLength = data.Length;
- requestScore.KeepAlive = true;
- Stream stream = requestScore.GetRequestStream();
- stream.Write(data, 0, data.Length);
- stream.Close();
- HttpWebResponse responseSorce;
- try
- {
- responseSorce = (HttpWebResponse)requestScore.GetResponse();
- }
- catch (WebException ex)
- {
- responseSorce = (HttpWebResponse)ex.Response;//得到请求网站的详细错误提示
- }
- StreamReader reader = new StreamReader(responseSorce.GetResponseStream(), Encoding.UTF8);
- string content = reader.ReadToEnd();
- requestScore.Abort();
- responseSorce.Close();
- responseSorce.Close();
- reader.Dispose();
- stream.Dispose();
- return content;
- }
- #endregion
网站得到Post过来的数据:
- /// <summary>
- /// 得到程序post过来的数据
- /// </summary>
- /// <returns></returns>
- private string GetPostContent()
- {
- string postStr = string.Empty;
- Stream inputStream = Request.InputStream;
- int contentLength = Request.ContentLength;
- int offset = 0;
- if (contentLength > 0)
- {
- byte[] buffer = new byte[contentLength];
- for (int i = inputStream.Read(buffer, offset, contentLength - offset); i > 0; i = inputStream.Read(buffer, offset, contentLength - offset))
- {
- offset += i;
- }
- UTF8Encoding encoding = new UTF8Encoding();
- postStr = encoding.GetString(buffer);
- }
- return postStr;
- }