c# Http请求之HttpClient
利用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的更多相关文章
- Flutter -------- 网络请求之HttpClient
今天来说说Flutter中的网络请求,HttpClient网络请求,包含get,post get var data; _get() async { Map newTitle; var response ...
- 网络请求框架----HttpClient的get,post和图片上传服务器
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的.最新的.功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议.HttpCli ...
- WebApi 异步请求(HttpClient)
还是那几句话: 学无止境,精益求精 十年河东,十年河西,莫欺少年穷 学历代表你的过去,能力代表你的现在,学习代表你的将来 废话不多说,直接进入正题: 今天公司总部要求各个分公司把短信接口对接上,所谓的 ...
- http请求,HttpClient,调用短信接口
项目中安全设置找回密码的功能,需要通过发送短信验证绑定手机,通过绑定的手机号验证并重新设置密码. 因为项目是通过maven管理的,所以需要在pom.xml文件中引入jar包, maven引入的jar包 ...
- C# 客户端网络请求 对HttpClient的封装
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/a1037949156/article/d ...
- SpringCloud gateway自定义请求的 httpClient
本文为博主原创,转载请注明出处: 引用 的 spring cloud gateway 的版本为 2.2.5 : SpringCloud gateway 在实现服务路由并请求的具体过程是在 org.sp ...
- 接口测试入门(2)--get和post初级请求/使用httpclient做一个获取信息list的请求(需要登录才可以)
抛去测试自动化的架构来,直接写单个测试用例的思路如下: 1.获取测试case的接口,对每一个接口的请求方式(get/post/delete/put)进行分析,是否需要参数(不同的用例设置不同的参数,如 ...
- HttpClient发送Get和Post请求
package JanGin.httpClient.demo; import java.io.IOException; import java.io.UnsupportedEncodingExcept ...
- 解决 HttpClient 模拟 http 的get 请求后 ,出现 403 错误
解决方法: URI uri = builder.build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); httpGet.setHead ...
随机推荐
- 安装mysql到ubuntu
Ubuntu 16.04上安装MySQL步骤: 如果你使用的是Ubuntu 16.04以前的版本,可以看这里:Ubuntu 14.04/15.10升级到Ubuntu 16.04 LTS.一. 安装My ...
- centos中安装php7
centos7下安装php7 php7 centos7 安装PHP7 首先安装一些必须的依赖,这里就不阐述了,后面文章再细说 yum install -y \ gcc-c++ autoconf \ l ...
- JSP笔记01——尝试
JSP ————> servlet 我的第1个Java Web应用程序——index.jsp 我的第2个Java Web应用程序——welcome-file 我的第3个Java Web应用程序— ...
- R中的数据重塑函数
1.去除重复数据 函数:duplicated(x, incomparables = FALSE, MARGIN = 1,fromLast = FALSE, ...),返回一个布尔值向量,重复数据的第一 ...
- 关闭Selinux 命令
在nginx 配置文件中,新增location中的内容,完成后,web上403报错 方法:关闭Selinux即可. Follow below steps: 虚拟机服务器环境补充: # vim/etc/ ...
- MongoDB快速入门(五)- Where子句
RDBMS Where子句等效于MongoDB 查询文档在一些条件的基础上,可以使用下面的操作 操作 语法 示例 RDBMS等效语句 Equality {<key>:<value&g ...
- java深入探究09-Filter,Listener,国际化
1.Filter过滤器 1)为是么有过滤器 开发项目中经常遇到直接登录主页面要判断用户是否合法,这类代码比较重复,可以通过过滤器来解决 2)过滤器原理生命周期 服务器创建过滤器对象->一个执行i ...
- UVA 580 Critical Mass (两次dp)
题意:一个字符串有n个位置每个位置只可能是L或者U,问你在所有可能出现的字符串中最少出现一次三个U连在一起的字符串的个数 题解:首先从左向右枚举每个位置i,保证i,i+1,i+2是U,并且i+2(不包 ...
- 【转】服务器.htaccess 详解以及 .htaccess 参数说明
htaccess文件(或者”分布式配置文件”)提供了针对目录改变配置的方法, 即,在一个特定的文档目录中放置一个包含一个或多个指令的文件, 以作用于此目录及其所有子目录.作为用户,所能使用的命令受到限 ...
- Python staticmethod
1 @staticmethod 静态方法 when this method is called, we don't pass an instance of the class to it (as we ...