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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Text;
  9.  
  10. namespace ConsoleApplication2
  11. {
  12. public class HTTPClientHelper
  13. {
  14. private static readonly HttpClient HttpClient;
  15. static HTTPClientHelper()
  16. {
  17. var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.None };
  18. HttpClient = new HttpClient(handler);
  19. }
  20.  
  21. /// <summary>
  22. /// get请求,可以对请求头进行多项设置
  23. /// </summary>
  24. /// <param name="paramArray"></param>
  25. /// <param name="url"></param>
  26. /// <returns></returns>
  27. public static string GetResponseByGet(List<KeyValuePair<string,string>> paramArray, string url)
  28. {
  29. string result = "";
  30.  
  31. var httpclient = HTTPClientHelper.HttpClient;
  32.  
  33. url = url + "?" + BuildParam(paramArray);
  34. var response = httpclient.GetAsync(url).Result;
  35. if (response.IsSuccessStatusCode)
  36. {
  37. Stream myResponseStream = response.Content.ReadAsStreamAsync().Result;
  38. StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
  39. result = myStreamReader.ReadToEnd();
  40. myStreamReader.Close();
  41. myResponseStream.Close();
  42. }
  43.  
  44. return result;
  45. }
  46. public static string GetResponseBySimpleGet(List<KeyValuePair<string,string>> paramArray, string url)
  47. {
  48.  
  49. var httpclient = HTTPClientHelper.HttpClient;
  50.  
  51. url = url + "?" + BuildParam(paramArray);
  52. var result = httpclient.GetStringAsync(url).Result;
  53. return result;
  54. }
  55.  
  56. public static string HttpPostRequestAsync(string Url, List<KeyValuePair<string, string>> paramArray, string ContentType = "application/x-www-form-urlencoded")
  57. {
  58. string result = "";
  59.  
  60. var postData = BuildParam(paramArray);
  61.  
  62. var data = Encoding.ASCII.GetBytes(postData);
  63.  
  64. try
  65. {
  66. using (HttpClient http = new HttpClient())
  67. {
  68. http.DefaultRequestHeaders.Add("User-Agent", @"Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)");
  69. http.DefaultRequestHeaders.Add("Accept", @"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
  70.  
  71. HttpResponseMessage message = null;
  72. using (Stream dataStream = new MemoryStream(data ?? new byte[]))
  73. {
  74. using (HttpContent content = new StreamContent(dataStream))
  75. {
  76. content.Headers.Add("Content-Type", ContentType);
  77. var task = http.PostAsync(Url, content);
  78. message = task.Result;
  79. }
  80. }
  81. if (message != null && message.StatusCode == System.Net.HttpStatusCode.OK)
  82. {
  83. using (message)
  84. {
  85. result = message.Content.ReadAsStringAsync().Result;
  86. }
  87. }
  88. }
  89. }
  90. catch (Exception ex)
  91. {
  92. Console.WriteLine(ex.Message);
  93. }
  94. return result;
  95. }
  96.  
  97. private static string Encode(string content, Encoding encode = null)
  98. {
  99. if (encode == null) return content;
  100.  
  101. return System.Web.HttpUtility.UrlEncode(content, Encoding.UTF8);
  102.  
  103. }
  104.  
  105. private static string BuildParam(List<KeyValuePair<string, string>> paramArray, Encoding encode = null)
  106. {
  107. string url = "";
  108.  
  109. if (encode == null) encode = Encoding.UTF8;
  110.  
  111. if (paramArray != null && paramArray.Count > )
  112. {
  113. var parms = "";
  114. foreach (var item in paramArray)
  115. {
  116. parms += string.Format("{0}={1}&", Encode(item.Key, encode), Encode(item.Value, encode));
  117. }
  118. if (parms != "")
  119. {
  120. parms = parms.TrimEnd('&');
  121. }
  122. url += parms;
  123.  
  124. }
  125. return url;
  126. }
  127. }
  128. }

有关更多的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. SpringMVC:学习笔记(3)——REST

    SpringMVC:学习笔记(3)——REST 了解REST风格 按照传统的开发方式,我们在实现CURD操作时,会写多个映射路径,比如对一本书的操作,我们会写多个URL,可能如下 web/delete ...

  2. iOS self 和 super 学习

    有人问我 这个问题 回答错了,题干大概是说 [self class] 和 [super class]打印结果 是不是一样的. 我睁着眼睛说是不一样的 .因为我明明记得 几天前 做 DFS 获取反射基类 ...

  3. MySQL修改管理员账户密码

    报错提示:ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)MySQL代理报错提示: ...

  4. Linux centos开机执行JAR Shell脚本

    Linux centos开机执行shell脚本 Linux centos开机执行 java  jar 1.编写jar执行脚本 vim start.sh 加入如下内容(根据自己真实路径与数据进行编写) ...

  5. window.name跨域

    window.name? 每一个页面都有一个自己的window,而window.name是window的名字. window.name跨域原理 window对象有个name属性,该属性有个特征:即在一 ...

  6. 使用git从本地上传至git码云远程仓库

    从 http://git-scm.com/download  下载window版的客户端.下载好,一步一步安装即可. 使用前的基本设置 git  config --global user.name & ...

  7. 20145240《Java程序设计》第三周学习总结

    20145240 <Java程序设计>第三周学习总结 教材学习内容总结 个人感觉第三周的学习量还是很大的,需要学习的内容更难了而且量也变多了,所以投入了更多的时间到Java的学习中去. 第 ...

  8. 如何隐藏tomcat命令窗口

    有两种方法: 一.修改tomcat中的文件参数,达到隐藏目的: 引用:TOMCAT_HOME\bin\setclasspath.bat 在文件的底部找到以下内容: set _RUNJAVA=" ...

  9. Windows系统 本地文件如何复制到远程服务器

    很多人在使用远程服务器的时候往往要将本地的文件传输到远程服务器内,方法有很多种,下面介绍下如何使用Windows自带的远程桌面连接程序将文件复制到远程服务器内. 1.首先,点击windows开始按钮, ...

  10. linux下bwa和samtools的安装与使用

    bwa的安装流程安装本软体总共需要完成以下两个软体的安装工作:1) BWA2) Samtools 1.BWA的安装a.下载BWA (download from BWA Source Forge ) h ...