C#爬虫基础之HttpClient获取HTTP请求与响应

一、概述

Net4.5以上的提供基本类,用于发送 HTTP 请求和接收来自通过 URI 确认的资源的 HTTP 响应。

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调用Oauth的授权接口获取access_token

1)OAuth使用的密码式

2)获取到access_token后才进行下一步

2.带着access_token调用接口

1)hearder上添加bearer方式的access_token

2)调用接口确保成功获取到返回的结果

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

    HttpClient httpClient = new HttpClient();

    // 设置请求头信息
    httpClient.DefaultRequestHeaders.Add("Host", host);
    httpClient.DefaultRequestHeaders.Add("Method", "Post");
    httpClient.DefaultRequestHeaders.Add("KeepAlive", "false");   // HTTP KeepAlive设为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();

    // 调用接口发起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数据
    ///
    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;
    }

    ///
    /// 发起post请求
    ///
    ///
    /// url
    /// post数据
    ///
    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发生异常: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;
    }

    ///
    /// 创建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;
    }
}

到此这篇关于C#使用HttpClient获取HTTP请求与响应的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • C#使用HttpClient的正确方式你了解吗

    目录 错误使用 New HttpClient static HttpClient 正确使用 错误使用 New HttpClient 如下面一段代码,日常开发中经常使用的 call http 方式,每次 new 一个 HttpClient using(var client = new HttpClient()) 先来做一个简单的测试,循环 call 一个 url ,代码如下 public async Task<string> GetXXXUrlAsync(string url) { var ht

  • c# HttpClient设置超时的步骤

    HttpClient作为官方推荐的http客户端,相比之前的WebClient和WebRequest好用了很多,但默认无法为每个请求单独设置超时,只能给HttpClient设置默认超时,使用起来不太方便. 声明:本文主要是翻译自THOMAS LEVESQUE'S .NET BLOG的文章:Better timeout handling with HttpClient. 由于工作原因,需要用c#,就语法层而言,c#确实比java优秀,一些库接口封装也更方便简洁.特别是HttpClient,结合了t

  • C#中HttpClient使用注意(预热与长连接)

    最近在测试一个第三方API,准备集成在我们的网站应用中.API的调用使用的是.NET中的HttpClient,由于这个API会在关键业务中用到,对调用API的整体响应速度有严格要求,所以对HttpClient有了格外的关注. 开始测试的时候,只在客户端通过HttpClient用PostAsync发了一个http post请求.测试时发现,从创建HttpClient实例,到发出请求,到读取到服务器的响应数据总耗时在2s左右,而且多次测试都是这样.2s的响应速度当然是无法让人接受的,我们希望至少控制

  • C#多线程TPL模式下使用HttpClient

    一.引言 我们有时侯需要在程序里面调用Http接口.请求http资源.编写http爬虫等的时候都需要在程序里面进行Http请求.很多人习惯的WebClient.HttpWebRequest在TPL下有很多用起来不方便的地方,TPL下推荐使用HttpClient(using System.Net.Http),而且在.NET Core下已经不在支持WebClient等. 1.发送Get请求 HttpClient发出Get请求获取文本响应,如下面的代码: // 实例化HttpClient对象 Http

  • C#客户端HttpClient请求认证及数据传输

    目录 一,授权认证 1. 基础认证示例 2. JWT 认证示例 3. Cookie 示例 二,请求类型 三,数据传输 1. Query 2. Header 3. 表单 4. JSON 5. 上传文件 一,授权认证 客户端请求服务器时,需要通过授权认证许可,方能获取服务器资源,目前比较常见的认证方式有 Basic .JWT.Cookie. HttpClient 是 C# 中的 HTTP/HTTPS 客户端,用于发送 HTTP 请求和接收来自通过 URI 确认的资源的 HTTP 响应.下面以具体代码

  • C# HttpClient Post参数同时上传文件的实现

    目录 HttpClient Post参数同时上传文件 Demo 如下 HttpClient上传文件到服务器(multipart/form-data) HttpClient Post参数同时上传文件 Demo 如下 using (var client = new HttpClient()) {     using (var multipartFormDataContent = new MultipartFormDataContent())     {         var values = ne

  • C#爬虫基础之HttpClient获取HTTP请求与响应

    一.概述 Net4.5以上的提供基本类,用于发送 HTTP 请求和接收来自通过 URI 确认的资源的 HTTP 响应. HttpClient是一个高级 API,用于包装其运行的每个平台上可用的较低级别功能. // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks. static readonly HttpClient client = new HttpC

  • Java爬虫Jsoup+httpclient获取动态生成的数据

    Java爬虫Jsoup+httpclient获取动态生成的数据 前面我们详细讲了一下Jsoup发现这玩意其实也就那样,只要是可以访问到的静态资源页面都可以直接用他来获取你所需要的数据,详情情跳转-Jsoup爬虫详解,但是很多时候网站为了防止数据被恶意爬取做了很多遮掩,比如说加密啊动态加载啊,这无形中给我们写的爬虫程序造成了很大的困扰,那么我们如何来突破这个梗获取我们急需的数据呢, 下面我们来详细讲解一下如何获取 String startPage="https://item.jd.com/1147

  • Python爬虫基础讲解之请求

    一.请求目标(URL) URL又叫作统一资源定位符,是用于完整地描述Internet上网页和其他资源的地址的一种方法.类似于windows的文件路径. 二.网址的组成: 1.http://:这个是协议,也就是HTTP超文本传输协议,也就是网页在网上传输的协议. 2.mail:这个是服务器名,代表着是一个邮箱服务器,所以是mail. 3.163.com:这个是域名,是用来定位网站的独一无二的名字. 4.mail.163.com:这个是网站名,由服务器名+域名组成. 5./:这个是根目录,也就是说,

  • java爬虫之使用HttpClient模拟浏览器发送请求方法详解

    0. 摘要 0.1 添加依赖 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> 0.2 代码 //1. 打开浏览器 创建httpclient对象 CloseableHttpClient httpCl

  • python爬虫基础教程:requests库(二)代码实例

    get请求 简单使用 import requests ''' 想要学习Python?Python学习交流群:973783996满足你的需求,资料都已经上传群文件,可以自行下载! ''' response = requests.get("https://www.baidu.com/") #text返回的是unicode的字符串,可能会出现乱码情况 # print(response.text) #content返回的是字节,需要解码 print(response.content.decod

  • python爬虫基础知识点整理

    首先爬虫是什么? 网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动的抓取万维网信息的程序或者脚本. 根据我的经验,要学习Python爬虫,我们要学习的共有以下几点: Python基础知识 Python中urllib和urllib2库的用法 Python正则表达式 Python爬虫框架Scrapy Python爬虫更高级的功能 1.Python基础学习 首先,我们要用Python写爬虫,肯定要了解Python的基础吧,万丈高楼平地起,

  • python爬虫基础之urllib的使用

    一.urllib 和 urllib2的关系 在python2中,主要使用urllib和urllib2,而python3对urllib和urllib2进行了重构,拆分成了urllib.request, urllib.parse, urllib.error,urllib.robotparser等几个子模块,这样的架构从逻辑和结构上说更加合理.urllib库无需安装,python3自带.python 3.x中将urllib库和urilib2库合并成了urllib库. urllib2.urlopen()

  • 在ASP.NET Core中应用HttpClient获取数据和内容

    在本文中,我们将学习如何在ASP.NET Core中集成和使用HttpClient.在学习不同HttpClient功能的同时使用Web API的资源.如何从Web API获取数据,以及如何直接使用HttpRequestMessage类来实现这些功能.在以后的文章中,我们将学习如何发送POST.PUT和DELETE请求,以及如何使用HttpClient发送PATCH请求. 要下载源代码,可以访问https://github.com/CodeMazeBlog/httpclient-aspnetcor

  • Python爬虫基础之requestes模块

    一.爬虫的流程 开始学习爬虫,我们必须了解爬虫的流程框架.在我看来爬虫的流程大概就是三步,即不论我们爬取的是什么数据,总是可以把爬虫的流程归纳总结为这三步: 1.指定 url,可以简单的理解为指定要爬取的网址 2.发送请求.requests 模块的请求一般为 get 和 post 3.将爬取的数据存储 二.requests模块的导入 因为 requests 模块属于外部库,所以需要我们自己导入库 导入的步骤: 1.右键Windows图标 2.点击"运行" 3.输入"cmd&q

  • python爬虫基础之简易网页搜集器

    简易网页搜集器 前面我们已经学会了简单爬取浏览器页面的爬虫.但事实上我们的需求当然不是爬取搜狗首页或是B站首页这么简单,再不济,我们都希望可以爬取某个特定的有信息的页面. 不知道在学会了爬取之后,你有没有跟我一样试着去爬取一些搜索页面,比如说百度.像这样的页面 注意我红笔划的部分,这是我打开的网页.现在我希望能爬取这一页的数据,按我们前面学的代码,应该是这样写的: import requests if __name__ == "__main__": # 指定URL url = &quo

随机推荐