一、不带参数请求
/// <summary> /// POST请求不带参数 /// </summary> /// <param name="url"></param> /// <returns></returns> public static string Post(string url) { string result;//返回结果 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream stream = response.GetResponseStream(); using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { result = reader.ReadToEnd(); } return result; }
二、带参数 post请求
/// <summary> /// post请求带参数 /// </summary> /// <param name="url"></param> /// <param name="param">参数字符串</param> /// <returns></returns> public static string Post(string url, string param) { //创建post请求 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST";//请求方式post request.ContentType = "application/json;charset=UTF-8";//链接类型 byte[] payload = Encoding.UTF8.GetBytes(param);//参数编码 request.ContentLength = payload.Length; //发送post的请求,写入参数 Stream writer = request.GetRequestStream(); writer.Write(payload, 0, payload.Length); writer.Close(); //接受返回来的数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream, Encoding.UTF8); string value = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); return value; }