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 协议最新的版本和建 ...
随机推荐
- Alpha冲刺(2/10)——2019.4.25
所属课程 软件工程1916|W(福州大学) 作业要求 Alpha冲刺(2/10)--2019.4.25 团队名称 待就业六人组 1.团队信息 团队名称:待就业六人组 团队描述:同舟共济扬帆起,乘风破浪 ...
- JWTtoken的原理以及在django中的应用
JWT 在用户注册或者登陆完成之后,记录用户状态,或者为用户创建身份凭证(功能类似于session的作用). 什么是JWT Json web token (JWT), 是为了在网络应用环境间传递声明而 ...
- SDWebImage 加载一些大的图片的时候导致程序崩溃
在 UIImage+MultiFormat这个类里面添加如下压缩方法, +(UIImage *)compressImageWith:(UIImage *)image { float imageWid ...
- Vue(二十二)vuex小案例(官网计数案例整合)
1.使用 vue-cli 创建项目(具体操作可以参考前面的文章) ... 2.下载 vuex - npm install vuex -S 3.将 vuex 添加到项目中 (1)在项目中创建store文 ...
- nodeJs --- web服务器创建
一.下载nodeJs http://nodejs.cn/download/ 根据自己的情况选择下载 然后在命令行中输入 node -v 看是否安装成功 (下载node时,会把npm包处理工具一起下) ...
- poj3253 Fence Repair(贪心+哈夫曼 经典)
https://vjudge.net/problem/POJ-3253 很经典的题,运用哈夫曼思想,想想很有道理!! 具体实现还是有点绕人,最后被long long卡了一下,看数据大小的时候单纯相乘了 ...
- 1、mysql初识
之前我们写代码需要存取信息时用的是文件可是用文件存取数据非常局限,今天我们将走进一个新的世界mysql 本片导航: 数据库由来 数据库概述 mysql介绍 下载安装 mysql软件基本管理 初识sql ...
- 11、python阶段测试
1.执行Python脚本的两种方式 如果想要永久保存代码,就要用文件的方式 如果想要调试代码,就要用交互式的方式 2.Pyhton单行注释和多行注释分别用什么? 单行注释:# 多行注释: '' &qu ...
- C# RabbitMQ优先级队列实战项目演练
一.需求背景 当用户在商城上进行下单支付,针对客户等级的不同和订单金额的大小划分客户级别,需要优先处理给标识为大订单的客户发送一份订单邮件提醒.那么我们应用程序如何解决这样的需求场景呢?今天阿笨给大家 ...
- Siamese网络
1. 对比损失函数(Contrastive Loss function) 孪生架构的目的不是对输入图像进行分类,而是区分它们.因此,分类损失函数(如交叉熵)不是最合适的选择,这种架构更适合 ...