最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#爬蟲基礎(chǔ)之HttpClient獲取HTTP請求與響應(yīng)

 更新時間:2022年05月27日 14:36:01   作者:springsnow  
這篇文章介紹了C#使用HttpClient獲取HTTP請求與響應(yīng)的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

一、概述

Net4.5以上的提供基本類,用于發(fā)送 HTTP 請求和接收來自通過 URI 確認(rèn)的資源的 HTTP 響應(yīng)。

HttpClient是一個高級 API,用于包裝其運行的每個平臺上可用的較低級別功能。

// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
 
static async Task Main()
{
  // Call asynchronous network methods in a try/catch block to handle exceptions.
  try    
  {
     HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
     response.EnsureSuccessStatusCode();
     string responseBody = await response.Content.ReadAsStringAsync();
     // Above three lines can be replaced with new helper method below
     // string responseBody = await client.GetStringAsync(uri);

     Console.WriteLine(responseBody);
  }  
  catch(HttpRequestException e)
  {
     Console.WriteLine("\nException Caught!");    
     Console.WriteLine("Message :{0} ",e.Message);
  }
}

二、HttpClient的使用

1.使用HttpClient調(diào)用Oauth的授權(quán)接口獲取access_token

1)OAuth使用的密碼式

2)獲取到access_token后才進行下一步

2.帶著access_token調(diào)用接口

1)hearder上添加bearer方式的access_token

2)調(diào)用接口確保成功獲取到返回的結(jié)果

try
{
    string host = ConfigurationManager.AppSettings["api_host"];
    string username = ConfigurationManager.AppSettings["api_username"];
    string password = ConfigurationManager.AppSettings["api_password"];

    HttpClient httpClient = new HttpClient();

    // 設(shè)置請求頭信息
    httpClient.DefaultRequestHeaders.Add("Host", host);
    httpClient.DefaultRequestHeaders.Add("Method", "Post");
    httpClient.DefaultRequestHeaders.Add("KeepAlive", "false");   // HTTP KeepAlive設(shè)為false,防止HTTP連接保持
    httpClient.DefaultRequestHeaders.Add("UserAgent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");

    //獲取token
    var tokenResponse = httpClient.PostAsync("http://" + host + "/token", new FormUrlEncodedContent(new Dictionary<string, string> {
                {"grant_type","password"},
                {"username", username},
                {"password", password}
            }));
    tokenResponse.Wait();
    tokenResponse.Result.EnsureSuccessStatusCode();
    var tokenRes = tokenResponse.Result.Content.ReadAsStringAsync();
    tokenRes.Wait();
    var token = Newtonsoft.Json.Linq.JObject.Parse(tokenRes.Result);
    var access_token = token["access_token"].ToString();

    // 調(diào)用接口發(fā)起POST請求
    var authenticationHeaderValue = new AuthenticationHeaderValue("bearer", access_token);
    httpClient.DefaultRequestHeaders.Authorization = authenticationHeaderValue;
var content = new StringContent(parameter);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    var response = httpClient.PostAsync("http://" + host + "/" + api_address, content);

    response.Wait();
    response.Result.EnsureSuccessStatusCode();
    var res = response.Result.Content.ReadAsStringAsync();
    res.Wait();return Newtonsoft.Json.JsonConvert.DeserializeObject(res.Result);
}
catch (Exception ex)
{

    return ResultEx.Init(ex.Message);
}

HttpClient 獲取圖片并保存到本機

class Program
{
    static void Main()
    {
        //圖片路徑:https://img.infinitynewtab.com/wallpaper/1.jpg
        string imgSourceURL = "https://img.infinitynewtab.com/wallpaper/";
        DownloadImags(imgSourceURL).Wait();
    }
    private static async Task DownloadImags(string url)
    {
        var client = new HttpClient();
        System.IO.FileStream fs;
        int a = 1;
        //文件名:序號+.jpg??芍付ǚ秶?,以下是獲取100.jpg~500.jpg.
        for (int i = 100; i <= 500; i++)
        {
            var uri = new Uri(Uri.EscapeUriString(url+i.ToString()+".jpg"));
            byte[] urlContents = await client.GetByteArrayAsync(uri);
            fs = new System.IO.FileStream(AppDomain.CurrentDomain.BaseDirectory + "\\images\\"+ i.ToString() + ".jpg",System.IO.FileMode.CreateNew);
            fs.Write(urlContents, 0, urlContents.Length);
            Console.WriteLine(a++);
        }
    }
}

以下為封裝的類庫

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;


public class HttpClientHelpClass
{
    /// 
    /// get請求
    /// 
    /// 
    /// 
    public static string GetResponse(string url, out string statusCode)
    {
        if (url.StartsWith("https"))
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

        var httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Accept.Add(      new MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage response = httpClient.GetAsync(url).Result;
        statusCode = response.StatusCode.ToString();
        if (response.IsSuccessStatusCode)
        {
            string result = response.Content.ReadAsStringAsync().Result;
            return result;
        }
        return null;
    }

    public static string RestfulGet(string url)
    {
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        // Get response
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            // Get the response stream
            StreamReader reader = new StreamReader(response.GetResponseStream());
            // Console application output
            return reader.ReadToEnd();
        }
    }

    public static T GetResponse(string url)
       where T : class, new()
    {
        if (url.StartsWith("https"))
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

       var httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Accept.Add(   new MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage response = httpClient.GetAsync(url).Result;

        T result = default(T);

        if (response.IsSuccessStatusCode)
        {
            Task<string> t = response.Content.ReadAsStringAsync();
            string s = t.Result;

            result = JsonConvert.DeserializeObject(s);
        }
        return result;
    }

    /// 
    /// post請求
    /// 
    /// 
    /// post數(shù)據(jù)
    /// 
    public static string PostResponse(string url, string postData, out string statusCode)
    {
        if (url.StartsWith("https"))
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

        HttpContent httpContent = new StringContent(postData);
        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        httpContent.Headers.ContentType.CharSet = "utf-8";

        HttpClient httpClient = new HttpClient();
        //httpClient..setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");

        HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

        statusCode = response.StatusCode.ToString();
        if (response.IsSuccessStatusCode)
        {
            string result = response.Content.ReadAsStringAsync().Result;
            return result;
        }

        return null;
    }

    /// 
    /// 發(fā)起post請求
    /// 
    /// 
    /// url
    /// post數(shù)據(jù)
    /// 
    public static T PostResponse(string url, string postData)
        where T : class, new()
    {
        if (url.StartsWith("https"))
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

        HttpContent httpContent = new StringContent(postData);
        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        HttpClient httpClient = new HttpClient();

        T result = default(T);

        HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

        if (response.IsSuccessStatusCode)
        {
            Task<string> t = response.Content.ReadAsStringAsync();
            string s = t.Result;

            result = JsonConvert.DeserializeObject(s);
        }
        return result;
    }


    /// 
    /// 反序列化Xml
    /// 
    /// 
    /// 
    /// 
    public static T XmlDeserialize(string xmlString)
        where T : class, new()
    {
        try
        {
            XmlSerializer ser = new XmlSerializer(typeof(T));
            using (StringReader reader = new StringReader(xmlString))
            {
                return (T)ser.Deserialize(reader);
            }
        }
        catch (Exception ex)
        {
            throw new Exception("XmlDeserialize發(fā)生異常:xmlString:" + xmlString + "異常信息:" + ex.Message);
        }

    }

    public static string PostResponse(string url, string postData, string token, string appId, string serviceURL, out string statusCode)
    {
        if (url.StartsWith("https"))
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

        HttpContent httpContent = new StringContent(postData);
        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        httpContent.Headers.ContentType.CharSet = "utf-8";

        httpContent.Headers.Add("token", token);
        httpContent.Headers.Add("appId", appId);
        httpContent.Headers.Add("serviceURL", serviceURL);


        HttpClient httpClient = new HttpClient();
        //httpClient..setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");

        HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

        statusCode = response.StatusCode.ToString();
        if (response.IsSuccessStatusCode)
        {
            string result = response.Content.ReadAsStringAsync().Result;
            return result;
        }

        return null;
    }

    /// 
    /// 修改API
    /// 
    /// 
    /// 
    /// 
    public static string KongPatchResponse(string url, string postData)
    {
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/x-www-form-urlencoded";
        httpWebRequest.Method = "PATCH";

        byte[] btBodys = Encoding.UTF8.GetBytes(postData);
        httpWebRequest.ContentLength = btBodys.Length;
        httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);

        HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        var streamReader = new StreamReader(httpWebResponse.GetResponseStream());
        string responseContent = streamReader.ReadToEnd();

        httpWebResponse.Close();
        streamReader.Close();
        httpWebRequest.Abort();
        httpWebResponse.Close();

        return responseContent;
    }

    /// 
    /// 創(chuàng)建API
    /// 
    /// 
    /// 
    /// 
    public static string KongAddResponse(string url, string postData)
    {
        if (url.StartsWith("https"))
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
        HttpContent httpContent = new StringContent(postData);
        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };
        var httpClient = new HttpClient();
        HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
        if (response.IsSuccessStatusCode)
        {
            string result = response.Content.ReadAsStringAsync().Result;
            return result;
        }
        return null;
    }

    /// 
    /// 刪除API
    /// 
    /// 
    /// 
    public static bool KongDeleteResponse(string url)
    {
        if (url.StartsWith("https"))
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

        var httpClient = new HttpClient();
        HttpResponseMessage response = httpClient.DeleteAsync(url).Result;
        return response.IsSuccessStatusCode;
    }

    /// 
    /// 修改或者更改API?    ?    
    /// 
    /// 
    /// 
    /// 
    public static string KongPutResponse(string url, string postData)
    {
        if (url.StartsWith("https"))
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

        HttpContent httpContent = new StringContent(postData);
        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };

        var httpClient = new HttpClient();
        HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;
        if (response.IsSuccessStatusCode)
        {
            string result = response.Content.ReadAsStringAsync().Result;
            return result;
        }
        return null;
    }

    /// 
    /// 檢索API
    /// 
    /// 
    /// 
    public static string KongSerchResponse(string url)
    {
        if (url.StartsWith("https"))
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

       var httpClient = new HttpClient();
        HttpResponseMessage response = httpClient.GetAsync(url).Result;
        if (response.IsSuccessStatusCode)
        {
            string result = response.Content.ReadAsStringAsync().Result;
            return result;
        }
        return null;
    }
}

到此這篇關(guān)于C#使用HttpClient獲取HTTP請求與響應(yīng)的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • C#實現(xiàn)文件分割和合并的示例詳解

    C#實現(xiàn)文件分割和合并的示例詳解

    這篇文章主要為大家詳細(xì)介紹了如何利用C#實現(xiàn)文件分割和合并的功能,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以跟隨小編一起了解一下
    2022-12-12
  • C#中數(shù)組Array,ArrayList,泛型List詳細(xì)對比

    C#中數(shù)組Array,ArrayList,泛型List詳細(xì)對比

    關(guān)于數(shù)組Array,ArrayList,泛型List,簡單的說數(shù)組就是值對象,它存儲數(shù)據(jù)元素類型的值的一系列位置.Arraylist和list可以提供添加,刪除,等操作的數(shù)據(jù). 具體如何進行選擇使用呢,我們來詳細(xì)探討下
    2016-06-06
  • C#使用PuppeteerSharp庫的示例代碼

    C#使用PuppeteerSharp庫的示例代碼

    PuppeteerSharp 是一個用于在 .NET 平臺上控制無頭(Headless) Chrome 瀏覽器的庫,本文主要為大家詳細(xì)介紹了C#中使用PuppeteerSharp庫的工具類,需要的可以了解下
    2023-12-12
  • C#中Convert.ToInt32()和int.Parse()的區(qū)別介紹

    C#中Convert.ToInt32()和int.Parse()的區(qū)別介紹

    Convert是一個類,繼承自system.Object;int是值類型,在本文為大家詳細(xì)介紹下它與int.Parse()的區(qū)別,感興趣的朋友可以參考下
    2013-10-10
  • Unity創(chuàng)建平鋪網(wǎng)格地圖的方法

    Unity創(chuàng)建平鋪網(wǎng)格地圖的方法

    這篇文章主要為大家詳細(xì)介紹了Unity創(chuàng)建平鋪網(wǎng)格地圖的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-07-07
  • C#儀器數(shù)據(jù)文件解析Excel文件的方法淺析(xls、xlsx)

    C#儀器數(shù)據(jù)文件解析Excel文件的方法淺析(xls、xlsx)

    這篇文章主要給大家介紹了關(guān)于C#儀器數(shù)據(jù)文件如何解析Excel文件的方法,包括解析xls、xlsx兩種格式,文中介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-10-10
  • c#入門之枚舉和結(jié)構(gòu)體使用詳解(控制臺接收字符串以相反的方向輸出)

    c#入門之枚舉和結(jié)構(gòu)體使用詳解(控制臺接收字符串以相反的方向輸出)

    這篇文章主要介紹了c#入門之枚舉和結(jié)構(gòu)體使用詳解,最后提供了編寫控制臺應(yīng)用程序接收字符串并做相應(yīng)處理的小示例,需要的朋友可以參考下
    2014-04-04
  • unity使用鏈表實現(xiàn)貪吃蛇游戲

    unity使用鏈表實現(xiàn)貪吃蛇游戲

    這篇文章主要為大家詳細(xì)介紹了unity使用鏈表實現(xiàn)貪吃蛇游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-04-04
  • C#集合之棧的用法

    C#集合之棧的用法

    這篇文章介紹了C#集合之棧的用法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-04-04
  • C# 實現(xiàn)PPT 每一頁轉(zhuǎn)成圖片過程解析

    C# 實現(xiàn)PPT 每一頁轉(zhuǎn)成圖片過程解析

    這篇文章主要介紹了C# 實現(xiàn)PPT 每一頁轉(zhuǎn)成圖片過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-09-09

最新評論

聂荣县| 延边| 通州区| 略阳县| 化隆| 来安县| 襄城县| 丹东市| 沂源县| 海城市| 南丰县| 屏南县| 华蓥市| 黄冈市| 张家界市| 洛扎县| 山丹县| 徐闻县| 曲阳县| 新郑市| 容城县| 德江县| 泽州县| 上犹县| 兴海县| 浦江县| 耒阳市| 峨眉山市| 洪泽县| 平果县| 绥阳县| 当雄县| 内丘县| 卢龙县| 临清市| 东城区| 阳城县| 阜平县| 晋州市| 兴海县| 华阴市|