一般人网络编程普遍用HttpWebRequest,类似下面的实现。我也一般都这样实现
string result = string.Empty; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(requesturl)); request.Method = method; request.ContentType = "application/json"; request.Headers["Authorization"] = AuthStr; if (!string.IsNullOrWhiteSpace(jsonstr)) { using (var requestStream = await request.GetRequestStreamAsync()) { var writer = new StreamWriter(requestStream); writer.Write(jsonstr); writer.Flush(); } } using (var resp = await request.GetResponseAsync()) { using (var responseStream = resp.GetResponseStream()) { var reader = new StreamReader(responseStream); result = reader.ReadToEnd(); } } return result;
但微软建议采用System.Net.Http.HttpClient类:MSDN链接
使用HttpClient类的确是比较简洁了。
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",AuthStr); HttpContent content = new StringContent(jsonstr,Encoding.UTF8); content.Headers.ContentType.CharSet = null; content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); System.Net.Http.HttpResponseMessage response = await client.PutAsync(new Uri(requesturl), content); response.EnsureSuccessStatusCode(); string responseBody = System.Text.RegularExpressions.Regex.Unescape(await response.Content.ReadAsStringAsync()); return responseBody;