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 ...
随机推荐
- SpringMVC:学习笔记(3)——REST
SpringMVC:学习笔记(3)——REST 了解REST风格 按照传统的开发方式,我们在实现CURD操作时,会写多个映射路径,比如对一本书的操作,我们会写多个URL,可能如下 web/delete ...
- iOS self 和 super 学习
有人问我 这个问题 回答错了,题干大概是说 [self class] 和 [super class]打印结果 是不是一样的. 我睁着眼睛说是不一样的 .因为我明明记得 几天前 做 DFS 获取反射基类 ...
- MySQL修改管理员账户密码
报错提示:ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)MySQL代理报错提示: ...
- Linux centos开机执行JAR Shell脚本
Linux centos开机执行shell脚本 Linux centos开机执行 java jar 1.编写jar执行脚本 vim start.sh 加入如下内容(根据自己真实路径与数据进行编写) ...
- window.name跨域
window.name? 每一个页面都有一个自己的window,而window.name是window的名字. window.name跨域原理 window对象有个name属性,该属性有个特征:即在一 ...
- 使用git从本地上传至git码云远程仓库
从 http://git-scm.com/download 下载window版的客户端.下载好,一步一步安装即可. 使用前的基本设置 git config --global user.name & ...
- 20145240《Java程序设计》第三周学习总结
20145240 <Java程序设计>第三周学习总结 教材学习内容总结 个人感觉第三周的学习量还是很大的,需要学习的内容更难了而且量也变多了,所以投入了更多的时间到Java的学习中去. 第 ...
- 如何隐藏tomcat命令窗口
有两种方法: 一.修改tomcat中的文件参数,达到隐藏目的: 引用:TOMCAT_HOME\bin\setclasspath.bat 在文件的底部找到以下内容: set _RUNJAVA=" ...
- Windows系统 本地文件如何复制到远程服务器
很多人在使用远程服务器的时候往往要将本地的文件传输到远程服务器内,方法有很多种,下面介绍下如何使用Windows自带的远程桌面连接程序将文件复制到远程服务器内. 1.首先,点击windows开始按钮, ...
- linux下bwa和samtools的安装与使用
bwa的安装流程安装本软体总共需要完成以下两个软体的安装工作:1) BWA2) Samtools 1.BWA的安装a.下载BWA (download from BWA Source Forge ) h ...