UWP开发--网络访问之HttpClient

网络请求–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();
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值