.Net Standard Http请求实例

倖福魔咒の 提交于 2020-01-06 15:45:40

原文

一 、.Net Standard http协议封装

程序集:

System.Net.Http.dll

命名 空间:System.Net.Http

HttpClient :http请求 发送类

FormUrlEncodedContent:Http请求表单参数

HttpResponseMessage:  http请求相应操作

HttpContent:http请求相应内容读取

 

二、Http Get请求示例

//使用 HttpClient创建Get请求
HttpClient client = new HttpClient();
Task<HttpResponseMessage> resp = client.GetAsync("http://www.gongjuji.net");
resp.ContinueWith(q =>
{
    //获取相应状态
    HttpResponseMessage respMsg = q.Result;
    Console.WriteLine(respMsg.StatusCode);

    //获取相应内容
    HttpContent respClient = respMsg.Content;
    respClient.ReadAsStringAsync().ContinueWith(str =>
    {
        string result = str.Result;

        Console.WriteLine(result);
    });
});

三、Http  Post请求示例

//使用HttpClient 创建Post请求
HttpClient client = new HttpClient();
//指定提交表单数据
List<KeyValuePair<String, String>> paramList = new List<KeyValuePair<String, String>>();
paramList.Add(new KeyValuePair<string, string>("Content", "e"));
FormUrlEncodedContent data = new FormUrlEncodedContent(paramList);

client.PostAsync("http://md5.gongjuji.net/common/md5encrypt", data)
    .ContinueWith(q =>
    {
        HttpResponseMessage respMsg = q.Result;
        //读取请求结果
        respMsg.Content.ReadAsStringAsync().ContinueWith(str =>
        {
            string result = str.Result;
            Console.WriteLine(result);
        });
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!