C# Http请求

一、 HttpWebRequest 方式

  支持.net 4.5 以下。一些老项目无法升级高版本的项目还用的到。例如支持XP系统的winfrom程序

可以携带cookie,使用HttpWebRequest的SupportsCookieContainer属性

public string HttpRequest()
{
    HttpWebResponse response = null;
    StreamReader resultReader = null;
    Dictionary<string, object> parameter = new Dictionary<string, object>()
    {
        { "p1","v1"},
        { "p2","v2"}
    };
    var parameterString = JsonConvert.SerializeObject(parameter);
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("htt://url");
        request.Method = "POST";
        request.ContentType = "application/json; charset=UTF-8";
        request.Headers = new WebHeaderCollection
        {
            { "Header1", "v1" },
            { "Header2", "v2" }
        };
        //设置参数
        byte[] data = Encoding.UTF8.GetBytes(parameterString);
        request.ContentLength = data.Length;
        using (Stream newStream = request.GetRequestStream())
        {
            newStream.Write(data, 0, data.Length);
        };
        //获取正确或错误结果
        try
        {
            response = (HttpWebResponse)request.GetResponse();
        }
        catch (WebException ex)
        {
            response = (HttpWebResponse)ex.Response;
        }
        Stream webStream = response.GetResponseStream();
        if (webStream == null)
        {
            throw new Exception("Network error");
        }
        int statsCode = (int)response.StatusCode;

        resultReader = new StreamReader(webStream, Encoding.UTF8);
        string responseContent = resultReader.ReadToEnd();

        //如果http请求响应非200,则异常 
        if (statsCode != 200)
        {
            throw new Exception(statsCode.ToString());
        }
        return responseContent;

    }
    catch (Exception e)
    {
        throw e;
    }
    finally
    {
        if (response != null)
            response.Close();
        if (resultReader != null)
            resultReader.Close();
    }
}
View Code

二、WebClient

  支持.net 4.5 以下。主要用于从特定的URI请求文件,WebClient很轻量级的访问Internet资源的类,在指定uri后可以发送和接受数据。WebClient提供了 DownLoadData,DownLoadFile,UploadData,UploadFile 等方法,同时通过了这些方法对应的异步方法,通过WebClient可以很方便地上传和下载文件

上传文件

{   /*
        这个方法会在对应的目录创建test.txt 文件
    */
    WebClient webClient = new WebClient();
    Stream stream = webClient.OpenRead("http://localhost:5743/file/test.txt");
    StreamWriter writer = new StreamWriter(stream);
    writer.WriteLine("哈哈哈哈哈哈");
    writer.Flush();
    writer.Close();
}

{   /*
        UploadFile把文件上传到指定目录
    */
    WebClient webClient = new WebClient();
    string file = @"d:download	emp.zip";
    byte[] responseArray = webClient.UploadFile("http://localhost:5743/rss/temp.zip", file);
    Console.WriteLine(Encoding.ASCII.GetString(responseArray));
}

{
    /*
        UploadData数据缓冲区上传到指定目录
    */
    WebClient webClient = new WebClient
    {
        Encoding = Encoding.UTF8
    };
    string file = @"d:download	emp.jpg";
    FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
    byte[] btye = new byte[fs.Length];
    fs.Read(btye, 0, btye.Length);
    byte[] responseArray = webClient.UploadData("http://localhost:5743/rss/temp.jpg", btye);
    Console.WriteLine(Encoding.UTF8.GetString(responseArray));
}
View Code

下载文件

{   /*
        DownloadData读取文件为byte[] 例如直接读取图片,文本
        DownloadString 直接读取文件为string,除了读文本,可以当做Get方法,直接读取html代码
        DownloadFile 下载文件到指定目录
    */
    WebClient webClient = new WebClient();
    byte[] bytes = webClient.DownloadData("http://localhost:5743/rss/temp.zip");
    string result = webClient.DownloadString("http://localhost:5743/rss/temp.zip");
    webClient.DownloadFile("http://localhost:5743/rss/temp.zip", @"d:download	emp.zip");
}

 三、HttpClient

   .net 4.5 开始提供基本类,用于发送 HTTP 请求和接收来自通过 URI 确认的资源的 HTTP 响应。Get方式,HttpClient提供 GetAsync,GetStringAsync,GetStreamAsync,GetStringAsync 方法。相对于Post 则要提供派生自httpContent类作为请求参数

Task.Run(async () =>
{
    HttpClient httpClient = new HttpClient();
    var parameter = new List<KeyValuePair<string, string>>() {
    new KeyValuePair<string, string>("userName","haosit"),
    new KeyValuePair<string, string>("password","haosit123")
};
    FormUrlEncodedContent content = new FormUrlEncodedContent(parameter);
    HttpResponseMessage response = await httpClient.PostAsync("http://localhost:5531", content);
    response.EnsureSuccessStatusCode();//如果响应错误则抛出异常
    string result = await response.Content.ReadAsStringAsync();
});

3.1 HttpContent 分别是:

1. FormUrlEncodedContent 使用应用程序/x-www 的窗体的 urlencoded MIME 类型编码的名称/值元组的 HTTP 内容。例如:application/x-www-form-urlencoded

2. MultipartContent 获取序列化使用多部分 HTTP 内容 / * 内容类型规范。例如:multipart/mixed; boundary="aba404d0-4a56-4cb7-be14-f0fb32b02030"

3. MultipartFormDataContent 的使用 multipart/form-data MIME 类型编码 HTTP 内容。例如:multipart/form-data; boundary="755ab5e6-1263-4e19-8b8b-da60f9ce78c2"

4. StringContent -基于 HTTP 内容字符串

5. StreamContent -基于 HTTP 内容流

6. ByteArrayContent -基于 HTTP 内容的字节数组

3.2 StringContent 

    StringContent 可以定义Content-Type

Dictionary<string, string> parameter = new Dictionary<string, string>()
{
    { "username","haosit"},
    { "password","haosit123"}
};
var http = new HttpClient();
string body = JsonConvert.SerializeObject(parameter);
var content = new StringContent(body, Encoding.UTF8, "application/json");
http.PostAsync("http://localhost:5531", content);

3.3 StreamContent 和 ByteArrayContent :httpClient 携带文件

 StreamContent,ByteArrayContent 可以作为MultipartContent,MultipartFormDataContent 携带的文件参数

var multipartFormDataContent = new MultipartFormDataContent();
var parameter =  new[]
{
    new KeyValuePair<string, string>("a", "3"),
    new KeyValuePair<string, string>("c", "2"),
    new KeyValuePair<string, string>("d", "2")
};
var http = new HttpClient();
foreach (var item in parameter)
{
    multipartFormDataContent.Add(new StringContent(item.Value),item.Key);
}
multipartFormDataContent.Add(new ByteArrayContent(File.ReadAllBytes(@"D:	est.jpg")),"test","test.jpg");
http.PostAsync("http://localhost:5531", multipartFormDataContent);

3.4 携带cookie

    handler.UseCookies=true(默认为true),默认的会自己带上cookies

{
    var handler = new HttpClientHandler() { UseCookies = true };
    var http = new HttpClient(handler);
}
原文地址:https://www.cnblogs.com/haosit/p/10607729.html