调用格式:
string url = "http://localhost:26314/HttpPost.ashx?"; string postDate = "userid=1&username=李四"; HttpPost(url, postDate);
c#代码:
/// <summary> /// Post请求 /// </summary> /// <param name="uri">请求的地址:</param> /// <param name="postData">参数</param> /// <returns></returns> string HttpPost(string uri, string postData) { WebRequest webRequest = WebRequest.Create(uri); webRequest.ContentType = "application/x-www-form-urlencoded"; // 设置请求的参数形式 webRequest.Method = "POST"; byte[] bytes = Encoding.UTF8.GetBytes(postData); //指定编码格式 webRequest.ContentLength = bytes.Length; // 设置请求参数的长度. Stream inStream = null; try { inStream = webRequest.GetRequestStream(); //取得发向服务器的流 inStream.Write(bytes, 0, bytes.Length); //发送 } catch (WebException ex) { return ex.Message.ToString(); } finally { if (inStream != null) { inStream.Close(); } } StreamReader readStream = null; try { WebResponse webResponse = webRequest.GetResponse(); // 等待返回结果 if (webResponse == null) { return null; } readStream = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.UTF8); return readStream.ReadToEnd().Trim(); } catch (WebException ex) { return ex.Message.ToString(); } finally { if (readStream != null) { readStream.Close(); } } }