c# httpclient
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Text;
- using System.Threading.Tasks;
- using System.Xml.Serialization;
- namespace SXYC.Common
- {
- public class HttpClientHelpClass
- {
- /// <summary>
- /// get请求
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public static string GetResponse(string url, out string statusCode)
- {
- if (url.StartsWith("https"))
- System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
- var httpClient = new HttpClient();
- httpClient.DefaultRequestHeaders.Accept.Add(
- new MediaTypeWithQualityHeaderValue("application/json"));
- HttpResponseMessage response = httpClient.GetAsync(url).Result;
- statusCode = response.StatusCode.ToString();
- if (response.IsSuccessStatusCode)
- {
- string result = response.Content.ReadAsStringAsync().Result;
- return result;
- }
- return null;
- }
- public static string RestfulGet(string url)
- {
- HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
- // Get response
- using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
- {
- // Get the response stream
- StreamReader reader = new StreamReader(response.GetResponseStream());
- // Console application output
- return reader.ReadToEnd();
- }
- }
- public static T GetResponse<T>(string url)
- where T : class, new()
- {
- if (url.StartsWith("https"))
- System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
- var httpClient = new HttpClient();
- httpClient.DefaultRequestHeaders.Accept.Add(
- new MediaTypeWithQualityHeaderValue("application/json"));
- HttpResponseMessage response = httpClient.GetAsync(url).Result;
- T result = default(T);
- if (response.IsSuccessStatusCode)
- {
- Task<string> t = response.Content.ReadAsStringAsync();
- string s = t.Result;
- result = JsonConvert.DeserializeObject<T>(s);
- }
- return result;
- }
- /// <summary>
- /// post请求
- /// </summary>
- /// <param name="url"></param>
- /// <param name="postData">post数据</param>
- /// <returns></returns>
- public static string PostResponse(string url, string postData, out string statusCode)
- {
- if (url.StartsWith("https"))
- System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
- HttpContent httpContent = new StringContent(postData);
- httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
- httpContent.Headers.ContentType.CharSet = "utf-8";
- HttpClient httpClient = new HttpClient();
- //httpClient..setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
- HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
- statusCode = response.StatusCode.ToString();
- if (response.IsSuccessStatusCode)
- {
- string result = response.Content.ReadAsStringAsync().Result;
- return result;
- }
- return null;
- }
- /// <summary>
- /// 发起post请求
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="url">url</param>
- /// <param name="postData">post数据</param>
- /// <returns></returns>
- public static T PostResponse<T>(string url, string postData)
- where T : class, new()
- {
- if (url.StartsWith("https"))
- System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
- HttpContent httpContent = new StringContent(postData);
- httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
- HttpClient httpClient = new HttpClient();
- T result = default(T);
- HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
- if (response.IsSuccessStatusCode)
- {
- Task<string> t = response.Content.ReadAsStringAsync();
- string s = t.Result;
- result = JsonConvert.DeserializeObject<T>(s);
- }
- return result;
- }
- /// <summary>
- /// 反序列化Xml
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="xmlString"></param>
- /// <returns></returns>
- public static T XmlDeserialize<T>(string xmlString)
- where T : class, new()
- {
- try
- {
- XmlSerializer ser = new XmlSerializer(typeof(T));
- using (StringReader reader = new StringReader(xmlString))
- {
- return (T)ser.Deserialize(reader);
- }
- }
- catch (Exception ex)
- {
- throw new Exception("XmlDeserialize发生异常:xmlString:" + xmlString + "异常信息:" + ex.Message);
- }
- }
- public static string PostResponse(string url, string postData, string token, string appId, string serviceURL, out string statusCode)
- {
- if (url.StartsWith("https"))
- System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
- HttpContent httpContent = new StringContent(postData);
- httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
- httpContent.Headers.ContentType.CharSet = "utf-8";
- httpContent.Headers.Add("token", token);
- httpContent.Headers.Add("appId", appId);
- httpContent.Headers.Add("serviceURL", serviceURL);
- HttpClient httpClient = new HttpClient();
- //httpClient..setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
- HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
- statusCode = response.StatusCode.ToString();
- if (response.IsSuccessStatusCode)
- {
- string result = response.Content.ReadAsStringAsync().Result;
- return result;
- }
- return null;
- }
- /// <summary>
- /// 修改API
- /// </summary>
- /// <param name="url"></param>
- /// <param name="postData"></param>
- /// <returns></returns>
- public static string KongPatchResponse(string url, string postData)
- {
- var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
- httpWebRequest.ContentType = "application/x-www-form-urlencoded";
- httpWebRequest.Method = "PATCH";
- byte[] btBodys = Encoding.UTF8.GetBytes(postData);
- httpWebRequest.ContentLength = btBodys.Length;
- httpWebRequest.GetRequestStream().Write(btBodys, , btBodys.Length);
- HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
- var streamReader = new StreamReader(httpWebResponse.GetResponseStream());
- string responseContent = streamReader.ReadToEnd();
- httpWebResponse.Close();
- streamReader.Close();
- httpWebRequest.Abort();
- httpWebResponse.Close();
- return responseContent;
- }
- /// <summary>
- /// 创建API
- /// </summary>
- /// <param name="url"></param>
- /// <param name="postData"></param>
- /// <returns></returns>
- public static string KongAddResponse(string url, string postData)
- {
- if (url.StartsWith("https"))
- ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
- HttpContent httpContent = new StringContent(postData);
- httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };
- var httpClient = new HttpClient();
- HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
- if (response.IsSuccessStatusCode)
- {
- string result = response.Content.ReadAsStringAsync().Result;
- return result;
- }
- return null;
- }
- /// <summary>
- /// 删除API
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public static bool KongDeleteResponse(string url)
- {
- if (url.StartsWith("https"))
- ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
- var httpClient = new HttpClient();
- HttpResponseMessage response = httpClient.DeleteAsync(url).Result;
- return response.IsSuccessStatusCode;
- }
- /// <summary>
- /// 修改或者更改API
- /// </summary>
- /// <param name="url"></param>
- /// <param name="postData"></param>
- /// <returns></returns>
- public static string KongPutResponse(string url, string postData)
- {
- if (url.StartsWith("https"))
- ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
- HttpContent httpContent = new StringContent(postData);
- httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };
- var httpClient = new HttpClient();
- HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;
- if (response.IsSuccessStatusCode)
- {
- string result = response.Content.ReadAsStringAsync().Result;
- return result;
- }
- return null;
- }
- /// <summary>
- /// 检索API
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public static string KongSerchResponse(string url)
- {
- if (url.StartsWith("https"))
- ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
- var httpClient = new HttpClient();
- HttpResponseMessage response = httpClient.GetAsync(url).Result;
- if (response.IsSuccessStatusCode)
- {
- string result = response.Content.ReadAsStringAsync().Result;
- return result;
- }
- return null;
- }
- }
- }
c# httpclient的更多相关文章
- HttpClient的替代者 - RestTemplate
需要的包 ,除了Spring的基础包外还用到json的包,这里的数据传输使用json格式 客户端和服务端都用到一下的包 <!-- Spring --> <dependency> ...
- 关于微软HttpClient使用,避免踩坑
最近公司对于WebApi的场景使用也越来越加大了,随之而来就是Api的客户端工具我们使用哪个?我们最常用的估计就是HttpClient,在微软类库中命名空间地址:System.Net.Http,是一个 ...
- 使用HttpClient的优解
新工作入职不满半周,目前仍然还在交接工作,适应环境当中,笔者不得不说看别人的源码实在是令人痛苦.所幸今天终于将大部分工作流畅地看了一遍,接下来就是熟悉框架技术的阶段了. 也正是在看源码的过程当中,有一 ...
- Java的异步HttpClient
上篇提到了高性能处理的关键是异步,而我们当中许多人依旧在使用同步模式的HttpClient访问第三方Web资源,我认为原因之一是:异步的HttpClient诞生较晚,许多人不知道:另外也可能是大多数W ...
- 揭秘Windows10 UWP中的httpclient接口[2]
阅读目录: 概述 如何选择 System.Net.Http Windows.Web.Http HTTP的常用功能 修改http头部 设置超时 使用身份验证凭据 使用客户端证书 cookie处理 概述 ...
- C#中HttpClient使用注意:预热与长连接
最近在测试一个第三方API,准备集成在我们的网站应用中.API的调用使用的是.NET中的HttpClient,由于这个API会在关键业务中用到,对调用API的整体响应速度有严格要求,所以对HttpCl ...
- HttpClient调用webApi时注意的小问题
HttpClient client = new HttpClient(); client.BaseAddress = new Uri(thisUrl); client.GetAsync("a ...
- HttpClient相关
HTTPClient的主页是http://jakarta.apache.org/commons/httpclient/,你可以在这里得到关于HttpClient更加详细的信息 HttpClient入门 ...
- Atitit.http httpclient实践java c# .net php attilax总结
Atitit.http httpclient实践java c# .net php attilax总结 1. Navtree>> net .http1 2. Httpclient理论1 2. ...
- 使用httpclient发送get或post请求
HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建 ...
随机推荐
- yii2 动态配置日志(log)
如果我们在项目中不允许修改配置文件中的 log 组件,那么动态配置 log 就变得很重要了,下面我分享一下动态配置 log 的方法: 默认的日志格式是 {date}{ip}{userID}{sessi ...
- ionic2引入cordova插件时提示 no provider for * 错误
直接上答案,如果出现这个错误,直接在component里添加一行代码: import { FileOpener } from '@ionic-native/file-opener'; @Compone ...
- 【转】Java基础:System.out.println与System.err.println的区别
同时使用了System.out.println与System.err.println()打印输入内容,结果看到的内容和预想的不一样,顺序与预料的不同并不是因为err和out的区别导致,而是因为他们是两 ...
- 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 ...
- CSS魔法堂:Flex布局
前言 Flex是Flexible Box的缩写,就是「弹性布局」.从2012年已经面世,但由于工作环境的原因一直没有详细了解.最近工作忙到头晕脑胀,是要学点新东西刺激一下大脑,打打鸡血. Flex就 ...
- mssql f_Split
mssql可以如下CREATE FUNCTION [dbo].[f_Split] ( @val varchar(max),@Splits varchar(100))RETURNS @Table TAB ...
- 初识Vulkan【转】
Vulkan是Khronos组织制定的“下一代”开放的图形显示API.是与DirectX12能够匹敌的GPU API标准. Vulkan是基于AMD的Mantle API演化而来,眼下Vulkan 1 ...
- Google Maps V3 之 路线服务
概述 您可以使用 DirectionsService 对象计算路线(使用各种交通方式).此对象与 Google Maps API 路线服务进行通信,该服务会接收路线请求并返回计算的结果.您可以自行处理 ...
- Android TextView中链接(link)点击事件的截取
布局文件xml <TextView package com.jayce.testlink; import android.net.Uri; import android.os.Bundle; i ...
- RobotFrameWork编写接口测试及如何断言
1. 前言 本篇是第一系列(Http接口自动化)的第五课程,如果对系列课程大纲不清楚的,可以查看<RobotFramework系列免费课程-开课了~>. 前面我们介绍了,在真正实施前,需先 ...