网络请求–HttpClient模拟浏览器的GET、POST请求
今天写uwp其中项目,涉及到网络访问,需要自己post信息并获取返回,但是网上很多尝试以后发现都不可行,出现request为空内容的情况,最后才找到一种比较靠谱的,写个博客记录下来
- GET请求
主要实现代码:
//Create an HTTP client object
Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
//Add a user-agent header to the GET request.
var headers = httpClient.DefaultRequestHeaders;
//The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
//especially if the header value is coming from user input.
string header = "ie";
if (!headers.UserAgent.TryParseAdd(header))
{
throw new Exception("Invalid header value: " + header);
}
header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
if (!headers.UserAgent.TryParseAdd(header))
{
throw new Exception("Invalid header value: " + header);
}
//需要请求的页面
Uri requestUri = new Uri("XXXXXXXXX");
//Send the GET request asynchronously and retrieve the response as a string.
Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
string httpResponseBody = "";
try
{
//Send the GET request
httpResponse = await httpClient.GetAsync(requestUri);
httpResponse.EnsureSuccessStatusCode();
//返回信息
httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
Debug.WriteLine(httpResponseBody);
}
catch (Exception ex)
{
await new MessageDialog(ex.Message).ShowAsync();
}
- POST请求
主要实现代码:
//Create an HTTP client object
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));
//xxxx为需要请求访问的页面
Uri requestUri = new Uri("xxxx");
//post信息
string infoJson;
string httpResponseBody = "";
try
{
HttpContent content = new StringContent(infoJson, Encoding.UTF8, "application/json");
//Send the post request
HttpResponseMessage response = await httpClient.PostAsync(requestUri, content);
response.EnsureSuccessStatusCode();
//读取返回信息
httpResponseBody = await response.Content.ReadAsStringAsync();
Debug.WriteLine(httpResponseBody);
}
catch (Exception ex)
{
await new MessageDialog(ex.Message).ShowAsync();
}