一、HttpClient方式,程序集 System.Net.Http.dll
GET:
HttpClient httpClient = new HttpClient();string result = httpClient.GetAsync("url?name=张三&age=18") .Result.Content.ReadAsStringAsync().Result;httpClient.Dispose();
POST:
HttpClient httpClient = new HttpClient();HttpContent httpContent = new StringContent("{\"name\":\"张三\",\"age\":\"18\"}");httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");//HttpContent httpContent = new FormUrlEncodedContent(Dictionary集合对象);//HttpContent httpContent = new MultipartFormDataContent();string result = httpClient.PostAsync("url", httpContent) .Result.Content.ReadAsStringAsync().Result;httpClient.Dispose();
二、HttpWebRequest方式
GET:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("url?name=张三&age=18");request.Method = "get";WebResponse response = request.GetResponse();StreamReader reader = new StreamReader(response.GetResponseStream());string result = reader.ReadToEnd();response.Close();reader.Dispose();
POST:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("url");request.ContentType = "application/x-www-form-urlencoded";request.Method = "post";byte[] byteData = UTF8Encoding.UTF8.GetBytes("name=张三&age=18");// Set the content length in the request headersrequest.ContentLength = byteData.Length;// Write data using (Stream postStream = request.GetRequestStream()){ postStream.Write(byteData, 0, byteData.Length);}// Get response WebResponse response = request.GetResponse();// Get the response streamStreamReader reader = new StreamReader(response.GetResponseStream());string result = reader.ReadToEnd();response.Close();reader.Dispose();
注:设置request.ContentLength可能会引起标头(Headers)丢失