利用HttpClient进行Http请求,基于此,简单地封装了下:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text; namespace ConsoleApplication2
{
public class HTTPClientHelper
{
private static readonly HttpClient HttpClient;
static HTTPClientHelper()
{
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.None };
HttpClient = new HttpClient(handler);
} /// <summary>
/// get请求,可以对请求头进行多项设置
/// </summary>
/// <param name="paramArray"></param>
/// <param name="url"></param>
/// <returns></returns>
public static string GetResponseByGet(List<KeyValuePair<string,string>> paramArray, string url)
{
string result = ""; var httpclient = HTTPClientHelper.HttpClient; url = url + "?" + BuildParam(paramArray);
var response = httpclient.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
Stream myResponseStream = response.Content.ReadAsStreamAsync().Result;
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
result = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
} return result;
}
public static string GetResponseBySimpleGet(List<KeyValuePair<string,string>> paramArray, string url)
{ var httpclient = HTTPClientHelper.HttpClient; url = url + "?" + BuildParam(paramArray);
var result = httpclient.GetStringAsync(url).Result;
return result;
} public static string HttpPostRequestAsync(string Url, List<KeyValuePair<string, string>> paramArray, string ContentType = "application/x-www-form-urlencoded")
{
string result = ""; var postData = BuildParam(paramArray); var data = Encoding.ASCII.GetBytes(postData); try
{
using (HttpClient http = new HttpClient())
{
http.DefaultRequestHeaders.Add("User-Agent", @"Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)");
http.DefaultRequestHeaders.Add("Accept", @"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); HttpResponseMessage message = null;
using (Stream dataStream = new MemoryStream(data ?? new byte[]))
{
using (HttpContent content = new StreamContent(dataStream))
{
content.Headers.Add("Content-Type", ContentType);
var task = http.PostAsync(Url, content);
message = task.Result;
}
}
if (message != null && message.StatusCode == System.Net.HttpStatusCode.OK)
{
using (message)
{
result = message.Content.ReadAsStringAsync().Result;
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return result;
} private static string Encode(string content, Encoding encode = null)
{
if (encode == null) return content; return System.Web.HttpUtility.UrlEncode(content, Encoding.UTF8); } private static string BuildParam(List<KeyValuePair<string, string>> paramArray, Encoding encode = null)
{
string url = ""; if (encode == null) encode = Encoding.UTF8; if (paramArray != null && paramArray.Count > )
{
var parms = "";
foreach (var item in paramArray)
{
parms += string.Format("{0}={1}&", Encode(item.Key, encode), Encode(item.Value, encode));
}
if (parms != "")
{
parms = parms.TrimEnd('&');
}
url += parms; }
return url;
}
}
}

有关更多的Http请求,请看这里:https://github.com/wangqiang3311/HttpRequestDemo

c# Http请求之HttpClient的更多相关文章

  1. Flutter -------- 网络请求之HttpClient

    今天来说说Flutter中的网络请求,HttpClient网络请求,包含get,post get var data; _get() async { Map newTitle; var response ...

  2. 网络请求框架----HttpClient的get,post和图片上传服务器

    HttpClient是Apache Jakarta Common下的子项目,用来提供高效的.最新的.功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议.HttpCli ...

  3. WebApi 异步请求(HttpClient)

    还是那几句话: 学无止境,精益求精 十年河东,十年河西,莫欺少年穷 学历代表你的过去,能力代表你的现在,学习代表你的将来 废话不多说,直接进入正题: 今天公司总部要求各个分公司把短信接口对接上,所谓的 ...

  4. http请求,HttpClient,调用短信接口

    项目中安全设置找回密码的功能,需要通过发送短信验证绑定手机,通过绑定的手机号验证并重新设置密码. 因为项目是通过maven管理的,所以需要在pom.xml文件中引入jar包, maven引入的jar包 ...

  5. C# 客户端网络请求 对HttpClient的封装

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/a1037949156/article/d ...

  6. SpringCloud gateway自定义请求的 httpClient

    本文为博主原创,转载请注明出处: 引用 的 spring cloud gateway 的版本为 2.2.5 : SpringCloud gateway 在实现服务路由并请求的具体过程是在 org.sp ...

  7. 接口测试入门(2)--get和post初级请求/使用httpclient做一个获取信息list的请求(需要登录才可以)

    抛去测试自动化的架构来,直接写单个测试用例的思路如下: 1.获取测试case的接口,对每一个接口的请求方式(get/post/delete/put)进行分析,是否需要参数(不同的用例设置不同的参数,如 ...

  8. HttpClient发送Get和Post请求

    package JanGin.httpClient.demo; import java.io.IOException; import java.io.UnsupportedEncodingExcept ...

  9. 解决 HttpClient 模拟 http 的get 请求后 ,出现 403 错误

    解决方法: URI uri = builder.build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); httpGet.setHead ...

随机推荐

  1. PHP基本语法,类基本函数

    C#中函数四要素返回类型,函数名,参数列表,函数体pulic void show()php函数定义1.最简单的定义function show(){echo "hello"}show ...

  2. loadrunner脚本篇——Run-time Settings之ContentCheck

    运用场景(很少用到): ContentCheck的设置可用来让VuGen检测存在错误的站点页面.如果被测的Web应用没有使用自定义的错误页面,那么这里不用添加规则,因为LR在回放时候,可以默认的捕捉到 ...

  3. iOS 结构简单清晰的 设置页面

    这个是也是看了人家的代码,觉得甚是简单清晰,也是比较容易扩展.拿来学习一下 效果展示: 重点有以下2处: 1 .建立groupModel 列清组元素:当前组list 集合, 是否有header 或者 ...

  4. 《Effective MySQL之SQL语句最优化》读书笔记——乱七八糟系列(给自己看)

    该书区别于诸如<MySQL技术内幕——InnoDB存储引擎>等书的一大特色是该书主要讲的是MySQL数据库中的索引技术,并分别讲了InnoDB.MyISAM.Memory三个存储引擎.其中 ...

  5. linux systemctl 指令 —— 阮一峰

    Systemd 指令 原文链接如果有效,请点击原文链接查看.原文:http://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-commands.ht ...

  6. 【HackerRank】Find the Median(Partition找到数组中位数)

    In the Quicksort challenges, you sorted an entire array. Sometimes, you just need specific informati ...

  7. 80211N、80211AC建链速率值(对应MCS)

    转:http://www.docin.com/p-1713976102.html?docfrom=rrela 注:各种技术对速率提升的贡献各项技术对提高传输速率的贡献如下:子载波数目增加: 802.1 ...

  8. Ubuntu 15.10环境下安装Hive

    1. 安装MySQL sudo tar -xzvf mysql-5.7.13-linux-glibc2.5-x86_64.tar.gz sudo mv mysql-5.7.13-linux-glibc ...

  9. INSPIRED启示录 读书笔记 - 第1章 关键角色及其职责

    现代软件产品团队 1.产品经理的主要职责分为两项:评估产品机会和定义要开发的产品 2.用户体验设计师(由多种角色组成,这里面最关键的是交互设计师)      交互设计师负责深入理解目标用户,设计有价值 ...

  10. Device Tree(一):背景介绍【转】

    本文转载自:http://www.wowotech.net/device_model/why-dt.html 一.前言 作为一个多年耕耘在linux 2.6.23内核的开发者,各个不同项目中各种不同周 ...