httpclient学习 get、post、put命令

http协议目前已经非常流行了,使用的地方已经非常多了。今天就UWP中http命令的使用做一个总结,如有不对之处请见谅。

UWP中使用Windows.Web.Http 命名空间空间以及所包含的API为UWP客户端提供统一的接口。

Get命令

get命令在windows开发中心上有一个demo。该demo基本可以满足日常的使用。正如本文前面提到的,Windows.Web.Http 命名空间允许 UWP 应用发送 GET 请求。以下代码段演示了如何使用 Windows.Web.Http.HttpClient 和Windows.Web.Http.HttpResponseMessage 类读取来自 GET 请求的响应,来将 GET 请求发送到 http://www.contoso.com。

    //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("http://www.contoso.com");
//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();
}
catch (Exception ex)
{
    httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
}

post命令

post命令在日常的使用中是最频繁的。大家可以通过下面的代码看一下post如何使用。

string url = "www.XXX.com"; //post的地址
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
                    {
                        {"client_id", “1233”},
                        {"client_secret", “4444”},
                    });

var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }
using (var http = new HttpClient(handler))
{
    //await异步等待回应
    try
    {
        HttpResponseMessage response = await http.PostAsync(url, content);
        if (response.StatusCode.GetHashCode() == 200)
        {
            OnRestRequestEvent(
            new RestEventArgs
            {
                StatuCode = stateCode,
                ExceptionInfo = "",
                sContentInfo = response.Content.ReadAsStringAsync().Result,
            });
        }
        else
        {
            OnRestRequestEvent(
           new RestEventArgs
           {
               StatuCode = stateCode,
               ExceptionInfo = response.Content.ReadAsStringAsync().Result,
               sContentInfo = response.Content.ReadAsStringAsync().Result,
           });
        }
    }
    catch (Exception errr)
    {
        OnRestRequestEvent(
            new RestEventArgs
            {
                StatuCode = -1,
                ExceptionInfo = errr.Message,
                sContentInfo = "",
            });
    }
}

这个例子拷贝自以前写的一个项目中,代码很简单,其中url和conent需要根据服务端的接口来确定。

PUT命令

这个命令使用比较少一些,网上资料也很少。put命令主要用于传输文件图片等。

HttpContent content = new  (filesteam);
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
using (var http = new HttpClient(handler))
{
    //await异步等待回应
    try
    {
        http.DefaultRequestHeaders.Add("fileInfo", {"fliename":"123.txt"});
        HttpResponseMessage response = await http.PutAsync(url, content);        
        if (response.StatusCode.GetHashCode()== 200)
        {
            OnRestRequestEvent(
            new RestEventArgs
            {
                StatuCode = stateCode,
                ExceptionInfo = "",
                sContentInfo = response.Content.ReadAsStringAsync().Result,
            });
        }
        else
        {
            OnRestRequestEvent(
           new RestEventArgs
           {
               StatuCode = stateCode,
               ExceptionInfo = response.Content.ReadAsStringAsync().Result,
               sContentInfo = response.Content.ReadAsStringAsync().Result,
           });
        }
    }
    catch (Exception errr)
    {
        OnRestRequestEvent(
            new RestEventArgs
            {
                StatuCode = -1,
                ExceptionInfo = errr.Message,
                sContentInfo = "",
            });
    }
}

put的用法和post很类似,唯一需要主要的就是put中content,content一般存储的是文件的流。这个流又分为 streamcontent和stringcontent。具体使用哪个流需要看服务器端的接口,否则会造成服务器端解析错误。原因是httpclient会根据流的类型选择url中头的参数,例如content-type等参数。

另外需要说明的是,如果你的url中需要添加头信息可以通过http.DefaultRequestHeaders.Add(“key”, “value”);来实现。

总之,接口不是你想用就能用,一定要根据服务端定义的接口说明来使用否则会让你欲仙欲死。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值