WebRequest如何发送http请求?
引用
using System.Net; using System.IO;
Base on Webreqution
public static string WebRequestByPost(string url, string contentType, string content, string Status) { string result; try { //1.Create request Uri uri = new Uri(url); WebRequest webRequest = WebRequest.Create(uri); //2.Set request type such like "application/json; charset=UTF-8";"text/xml; charset=utf-8"; webRequest.ContentType = contentType; webRequest.Method = Status;//POST or Get //3.If you need to set parameters or not dont need this using (Stream requestStream = webRequest.GetRequestStream()) { byte[] paramBytes = Encoding.UTF8.GetBytes(content.ToString()); requestStream.Write(paramBytes, 0, paramBytes.Length); } //4.Recived responce of request WebResponse webResponse = webRequest.GetResponse(); using (StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8)) { result = myStreamReader.ReadToEnd(); } } catch (Exception e) { throw new Exception("发送请求失败!"); } return result; }
总结:使用方便,简介,缺点是请求无法设置cookie。