1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Net.Http.Headers;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using System.Xml.Serialization;
  12.  
  13. namespace SXYC.Common
  14. {
  15. public class HttpClientHelpClass
  16. {
  17. /// <summary>
  18. /// get请求
  19. /// </summary>
  20. /// <param name="url"></param>
  21. /// <returns></returns>
  22. public static string GetResponse(string url, out string statusCode)
  23. {
  24. if (url.StartsWith("https"))
  25. System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  26.  
  27. var httpClient = new HttpClient();
  28. httpClient.DefaultRequestHeaders.Accept.Add(
  29. new MediaTypeWithQualityHeaderValue("application/json"));
  30. HttpResponseMessage response = httpClient.GetAsync(url).Result;
  31. statusCode = response.StatusCode.ToString();
  32. if (response.IsSuccessStatusCode)
  33. {
  34. string result = response.Content.ReadAsStringAsync().Result;
  35. return result;
  36. }
  37. return null;
  38. }
  39.  
  40. public static string RestfulGet(string url)
  41. {
  42. HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  43. // Get response
  44. using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
  45. {
  46. // Get the response stream
  47. StreamReader reader = new StreamReader(response.GetResponseStream());
  48. // Console application output
  49. return reader.ReadToEnd();
  50. }
  51. }
  52.  
  53. public static T GetResponse<T>(string url)
  54. where T : class, new()
  55. {
  56. if (url.StartsWith("https"))
  57. System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  58.  
  59. var httpClient = new HttpClient();
  60. httpClient.DefaultRequestHeaders.Accept.Add(
  61. new MediaTypeWithQualityHeaderValue("application/json"));
  62. HttpResponseMessage response = httpClient.GetAsync(url).Result;
  63.  
  64. T result = default(T);
  65.  
  66. if (response.IsSuccessStatusCode)
  67. {
  68. Task<string> t = response.Content.ReadAsStringAsync();
  69. string s = t.Result;
  70.  
  71. result = JsonConvert.DeserializeObject<T>(s);
  72. }
  73. return result;
  74. }
  75.  
  76. /// <summary>
  77. /// post请求
  78. /// </summary>
  79. /// <param name="url"></param>
  80. /// <param name="postData">post数据</param>
  81. /// <returns></returns>
  82. public static string PostResponse(string url, string postData, out string statusCode)
  83. {
  84. if (url.StartsWith("https"))
  85. System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  86.  
  87. HttpContent httpContent = new StringContent(postData);
  88. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  89. httpContent.Headers.ContentType.CharSet = "utf-8";
  90.  
  91. HttpClient httpClient = new HttpClient();
  92. //httpClient..setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
  93.  
  94. HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
  95.  
  96. statusCode = response.StatusCode.ToString();
  97. if (response.IsSuccessStatusCode)
  98. {
  99. string result = response.Content.ReadAsStringAsync().Result;
  100. return result;
  101. }
  102.  
  103. return null;
  104. }
  105.  
  106. /// <summary>
  107. /// 发起post请求
  108. /// </summary>
  109. /// <typeparam name="T"></typeparam>
  110. /// <param name="url">url</param>
  111. /// <param name="postData">post数据</param>
  112. /// <returns></returns>
  113. public static T PostResponse<T>(string url, string postData)
  114. where T : class, new()
  115. {
  116. if (url.StartsWith("https"))
  117. System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  118.  
  119. HttpContent httpContent = new StringContent(postData);
  120. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  121. HttpClient httpClient = new HttpClient();
  122.  
  123. T result = default(T);
  124.  
  125. HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
  126.  
  127. if (response.IsSuccessStatusCode)
  128. {
  129. Task<string> t = response.Content.ReadAsStringAsync();
  130. string s = t.Result;
  131.  
  132. result = JsonConvert.DeserializeObject<T>(s);
  133. }
  134. return result;
  135. }
  136.  
  137. /// <summary>
  138. /// 反序列化Xml
  139. /// </summary>
  140. /// <typeparam name="T"></typeparam>
  141. /// <param name="xmlString"></param>
  142. /// <returns></returns>
  143. public static T XmlDeserialize<T>(string xmlString)
  144. where T : class, new()
  145. {
  146. try
  147. {
  148. XmlSerializer ser = new XmlSerializer(typeof(T));
  149. using (StringReader reader = new StringReader(xmlString))
  150. {
  151. return (T)ser.Deserialize(reader);
  152. }
  153. }
  154. catch (Exception ex)
  155. {
  156. throw new Exception("XmlDeserialize发生异常:xmlString:" + xmlString + "异常信息:" + ex.Message);
  157. }
  158.  
  159. }
  160.  
  161. public static string PostResponse(string url, string postData, string token, string appId, string serviceURL, out string statusCode)
  162. {
  163. if (url.StartsWith("https"))
  164. System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  165.  
  166. HttpContent httpContent = new StringContent(postData);
  167. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  168. httpContent.Headers.ContentType.CharSet = "utf-8";
  169.  
  170. httpContent.Headers.Add("token", token);
  171. httpContent.Headers.Add("appId", appId);
  172. httpContent.Headers.Add("serviceURL", serviceURL);
  173.  
  174. HttpClient httpClient = new HttpClient();
  175. //httpClient..setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
  176.  
  177. HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
  178.  
  179. statusCode = response.StatusCode.ToString();
  180. if (response.IsSuccessStatusCode)
  181. {
  182. string result = response.Content.ReadAsStringAsync().Result;
  183. return result;
  184. }
  185.  
  186. return null;
  187. }
  188.  
  189. /// <summary>
  190. /// 修改API
  191. /// </summary>
  192. /// <param name="url"></param>
  193. /// <param name="postData"></param>
  194. /// <returns></returns>
  195. public static string KongPatchResponse(string url, string postData)
  196. {
  197. var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
  198. httpWebRequest.ContentType = "application/x-www-form-urlencoded";
  199. httpWebRequest.Method = "PATCH";
  200.  
  201. byte[] btBodys = Encoding.UTF8.GetBytes(postData);
  202. httpWebRequest.ContentLength = btBodys.Length;
  203. httpWebRequest.GetRequestStream().Write(btBodys, , btBodys.Length);
  204.  
  205. HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  206. var streamReader = new StreamReader(httpWebResponse.GetResponseStream());
  207. string responseContent = streamReader.ReadToEnd();
  208.  
  209. httpWebResponse.Close();
  210. streamReader.Close();
  211. httpWebRequest.Abort();
  212. httpWebResponse.Close();
  213.  
  214. return responseContent;
  215. }
  216.  
  217. /// <summary>
  218. /// 创建API
  219. /// </summary>
  220. /// <param name="url"></param>
  221. /// <param name="postData"></param>
  222. /// <returns></returns>
  223. public static string KongAddResponse(string url, string postData)
  224. {
  225. if (url.StartsWith("https"))
  226. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  227. HttpContent httpContent = new StringContent(postData);
  228. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };
  229. var httpClient = new HttpClient();
  230. HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
  231. if (response.IsSuccessStatusCode)
  232. {
  233. string result = response.Content.ReadAsStringAsync().Result;
  234. return result;
  235. }
  236. return null;
  237. }
  238.  
  239. /// <summary>
  240. /// 删除API
  241. /// </summary>
  242. /// <param name="url"></param>
  243. /// <returns></returns>
  244. public static bool KongDeleteResponse(string url)
  245. {
  246. if (url.StartsWith("https"))
  247. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  248.  
  249. var httpClient = new HttpClient();
  250. HttpResponseMessage response = httpClient.DeleteAsync(url).Result;
  251. return response.IsSuccessStatusCode;
  252. }
  253.  
  254. /// <summary>
  255. /// 修改或者更改API 
  256. /// </summary>
  257. /// <param name="url"></param>
  258. /// <param name="postData"></param>
  259. /// <returns></returns>
  260. public static string KongPutResponse(string url, string postData)
  261. {
  262. if (url.StartsWith("https"))
  263. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  264.  
  265. HttpContent httpContent = new StringContent(postData);
  266. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };
  267.  
  268. var httpClient = new HttpClient();
  269. HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;
  270. if (response.IsSuccessStatusCode)
  271. {
  272. string result = response.Content.ReadAsStringAsync().Result;
  273. return result;
  274. }
  275. return null;
  276. }
  277.  
  278. /// <summary>
  279. /// 检索API
  280. /// </summary>
  281. /// <param name="url"></param>
  282. /// <returns></returns>
  283. public static string KongSerchResponse(string url)
  284. {
  285. if (url.StartsWith("https"))
  286. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  287.  
  288. var httpClient = new HttpClient();
  289. HttpResponseMessage response = httpClient.GetAsync(url).Result;
  290. if (response.IsSuccessStatusCode)
  291. {
  292. string result = response.Content.ReadAsStringAsync().Result;
  293. return result;
  294. }
  295. return null;
  296. }
  297. }
  298. }

c# httpclient的更多相关文章

  1. HttpClient的替代者 - RestTemplate

    需要的包 ,除了Spring的基础包外还用到json的包,这里的数据传输使用json格式 客户端和服务端都用到一下的包 <!-- Spring --> <dependency> ...

  2. 关于微软HttpClient使用,避免踩坑

    最近公司对于WebApi的场景使用也越来越加大了,随之而来就是Api的客户端工具我们使用哪个?我们最常用的估计就是HttpClient,在微软类库中命名空间地址:System.Net.Http,是一个 ...

  3. 使用HttpClient的优解

    新工作入职不满半周,目前仍然还在交接工作,适应环境当中,笔者不得不说看别人的源码实在是令人痛苦.所幸今天终于将大部分工作流畅地看了一遍,接下来就是熟悉框架技术的阶段了. 也正是在看源码的过程当中,有一 ...

  4. Java的异步HttpClient

    上篇提到了高性能处理的关键是异步,而我们当中许多人依旧在使用同步模式的HttpClient访问第三方Web资源,我认为原因之一是:异步的HttpClient诞生较晚,许多人不知道:另外也可能是大多数W ...

  5. 揭秘Windows10 UWP中的httpclient接口[2]

    阅读目录: 概述 如何选择 System.Net.Http Windows.Web.Http HTTP的常用功能 修改http头部 设置超时 使用身份验证凭据 使用客户端证书 cookie处理 概述 ...

  6. C#中HttpClient使用注意:预热与长连接

    最近在测试一个第三方API,准备集成在我们的网站应用中.API的调用使用的是.NET中的HttpClient,由于这个API会在关键业务中用到,对调用API的整体响应速度有严格要求,所以对HttpCl ...

  7. HttpClient调用webApi时注意的小问题

    HttpClient client = new HttpClient(); client.BaseAddress = new Uri(thisUrl); client.GetAsync("a ...

  8. HttpClient相关

    HTTPClient的主页是http://jakarta.apache.org/commons/httpclient/,你可以在这里得到关于HttpClient更加详细的信息 HttpClient入门 ...

  9. Atitit.http httpclient实践java c# .net php attilax总结

    Atitit.http httpclient实践java c# .net php attilax总结 1. Navtree>> net .http1 2. Httpclient理论1 2. ...

  10. 使用httpclient发送get或post请求

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

随机推荐

  1. yii2 动态配置日志(log)

    如果我们在项目中不允许修改配置文件中的 log 组件,那么动态配置 log 就变得很重要了,下面我分享一下动态配置 log 的方法: 默认的日志格式是 {date}{ip}{userID}{sessi ...

  2. ionic2引入cordova插件时提示 no provider for * 错误

    直接上答案,如果出现这个错误,直接在component里添加一行代码: import { FileOpener } from '@ionic-native/file-opener'; @Compone ...

  3. 【转】Java基础:System.out.println与System.err.println的区别

    同时使用了System.out.println与System.err.println()打印输入内容,结果看到的内容和预想的不一样,顺序与预料的不同并不是因为err和out的区别导致,而是因为他们是两 ...

  4. CentOS下双网卡双IP不同IP段配置

    环境: eth0:10.0.7.2  gw :10.0.7.254 netmask:255.255.255.0 eth1:168.6.101.2    gw :168.6.101.254    net ...

  5. CSS魔法堂:Flex布局

    前言  Flex是Flexible Box的缩写,就是「弹性布局」.从2012年已经面世,但由于工作环境的原因一直没有详细了解.最近工作忙到头晕脑胀,是要学点新东西刺激一下大脑,打打鸡血. Flex就 ...

  6. mssql f_Split

    mssql可以如下CREATE FUNCTION [dbo].[f_Split] ( @val varchar(max),@Splits varchar(100))RETURNS @Table TAB ...

  7. 初识Vulkan【转】

    Vulkan是Khronos组织制定的“下一代”开放的图形显示API.是与DirectX12能够匹敌的GPU API标准. Vulkan是基于AMD的Mantle API演化而来,眼下Vulkan 1 ...

  8. Google Maps V3 之 路线服务

    概述 您可以使用 DirectionsService 对象计算路线(使用各种交通方式).此对象与 Google Maps API 路线服务进行通信,该服务会接收路线请求并返回计算的结果.您可以自行处理 ...

  9. Android TextView中链接(link)点击事件的截取

    布局文件xml <TextView package com.jayce.testlink; import android.net.Uri; import android.os.Bundle; i ...

  10. RobotFrameWork编写接口测试及如何断言

    1. 前言 本篇是第一系列(Http接口自动化)的第五课程,如果对系列课程大纲不清楚的,可以查看<RobotFramework系列免费课程-开课了~>. 前面我们介绍了,在真正实施前,需先 ...