C# ASP.NET Core使用HttpClient的同步和异步请求
引用 Newtonsoft.Json
// Post请求
public string PostResponse(string url,string postData,out string statusCode)
{
string result = string.Empty;
//设置Http的正文
HttpContent httpContent = new StringContent(postData);
//设置Http的内容标头
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
//设置Http的内容标头的字符
httpContent.Headers.ContentType.CharSet = "utf-8";
using(HttpClient httpClient=new HttpClient())
{
//异步Post
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
//输出Http响应状态码
statusCode = response.StatusCode.ToString();
//确保Http响应成功
if (response.IsSuccessStatusCode)
{
//异步读取json
result = response.Content.ReadAsStringAsync().Result;
}
}
return result;
} // 泛型:Post请求
public T PostResponse<T>(string url,string postData) where T:class,new()
{
T result = default(T); HttpContent httpContent = new StringContent(postData);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
httpContent.Headers.ContentType.CharSet = "utf-8";
using(HttpClient httpClient=new HttpClient())
{
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; if (response.IsSuccessStatusCode)
{
Task<string> t = response.Content.ReadAsStringAsync();
string s = t.Result;
//Newtonsoft.Json
string json = JsonConvert.DeserializeObject(s).ToString();
result = JsonConvert.DeserializeObject<T>(json);
}
}
return result;
}
post
参数为键值对:var content = new FormUrlEncodedContent(postData);
使用HttpClient 请求的时候碰到个问题不知道是什么异常,用HttpWebResponse请求才获取到异常,设置ServicePointManager可以用,参考下面这个
/// <summary>
/// http请求接口
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <returns></returns>
public T httpClientPost<T>(string url, string postData) where T : class, new()
{ T result = default(T);
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
HttpContent httpContent = new StringContent(postData);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
httpContent.Headers.ContentType.CharSet = "utf-8";
using (HttpClient httpClient = new HttpClient())
{
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; if (response.IsSuccessStatusCode)
{
Task<string> t = response.Content.ReadAsStringAsync();
string s = t.Result;
//Newtonsoft.Json
string json = JsonConvert.DeserializeObject(s).ToString();
result = JsonConvert.DeserializeObject<T>(json);
} } return result; } public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{ // 总是接受
return true;
} /// <summary>
/// http请求接口
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="bodyString"></param>
/// <returns></returns>
public VMDataResponse<T> HttpPost<T>(string url, string bodyString)
{
var result = new VMDataResponse<T>();
try
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
var request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
byte[] buffer = Encoding.UTF8.GetBytes(bodyString);
request.ContentLength = buffer.Length;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
request.GetRequestStream().Write(buffer, , buffer.Length);
var response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
{
result.msg = "错误:Respose返回不是StatusCode!=OK";
result.status = ;
logger.Error(result.msg);
return result;
}
using (var ss = response.GetResponseStream())
{
byte[] rbs = new byte[];
int count = ;
string str = "";
while (ss != null && (count = ss.Read(rbs, , rbs.Length)) > )
{
str += Encoding.UTF8.GetString(rbs, , count);
}
var msg = str;
//logger.Error("返回信息" + msg);
if (!string.IsNullOrWhiteSpace(msg))
{
result.data = JsonConvert.DeserializeObject<T>(msg);
return result;
}
}
}
catch (Exception ex)
{
result.msg = "错误:请求出现异常消息:" + ex.Message;
result.status = ;
logger.Error(result.msg);
return result;
}
return result;
}
post
get:
// 泛型:Get请求
public T GetResponse<T>(string url) where T :class,new()
{
T result = default(T); using (HttpClient httpClient=new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.GetAsync(url).Result; if (response.IsSuccessStatusCode)
{
Task<string> t = response.Content.ReadAsStringAsync();
string s = t.Result;
string json = JsonConvert.DeserializeObject(s).ToString();
result = JsonConvert.DeserializeObject<T>(json);
}
}
return result;
} // Get请求
public string GetResponse(string url, out string statusCode)
{
string result = string.Empty; using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = httpClient.GetAsync(url).Result;
statusCode = response.StatusCode.ToString(); if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
}
}
return result;
}
put:
// Put请求
public string PutResponse(string url, string putData, out string statusCode)
{
string result = string.Empty;
HttpContent httpContent = new StringContent(putData);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
httpContent.Headers.ContentType.CharSet = "utf-8";
using (HttpClient httpClient = new HttpClient())
{
HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;
statusCode = response.StatusCode.ToString();
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
}
}
return result;
} // 泛型:Put请求
public T PutResponse<T>(string url, string putData) where T : class, new()
{
T result = default(T);
HttpContent httpContent = new StringContent(putData);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
httpContent.Headers.ContentType.CharSet = "utf-8";
using(HttpClient httpClient=new HttpClient())
{
HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result; if (response.IsSuccessStatusCode)
{
Task<string> t = response.Content.ReadAsStringAsync();
string s = t.Result;
string json = JsonConvert.DeserializeObject(s).ToString();
result = JsonConvert.DeserializeObject<T>(json);
}
}
return result;
}
https://blog.csdn.net/sun_zeliang/article/details/81587835
https://blog.csdn.net/baidu_32739019/article/details/78679129
ASP.NET Core使用HttpClient的同步和异步请求
ASP.NET Core使用HttpClient的同步和异步请求 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;
using System.Threading.Tasks;
using System.Web; namespace Common
{
public class HttpHelper
{/// <summary>
/// 发起POST同步请求
///
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
/// <param name="headers">填充消息头</param>
/// <returns></returns>
public static string HttpPost(string url, string postData = null, string contentType = null, int timeOut = , Dictionary<string, string> headers = null)
{
postData = postData ?? "";
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
} /// <summary>
/// 发起POST异步请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
/// <param name="headers">填充消息头</param>
/// <returns></returns>
public static async Task<string> HttpPostAsync(string url, string postData = null, string contentType = null, int timeOut = , Dictionary<string, string> headers = null)
{
postData = postData ?? "";
using (HttpClient client = new HttpClient())
{
client.Timeout = new TimeSpan(, , timeOut);
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); HttpResponseMessage response = await client.PostAsync(url, httpContent);
return await response.Content.ReadAsStringAsync();
}
}
} /// <summary>
/// 发起GET同步请求
/// </summary>
/// <param name="url"></param>
/// <param name="headers"></param>
/// <param name="contentType"></param>
/// <returns></returns>
public static string HttpGet(string url, string contentType = null, Dictionary<string, string> headers = null)
{
using (HttpClient client = new HttpClient())
{
if (contentType != null)
client.DefaultRequestHeaders.Add("ContentType", contentType);
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
HttpResponseMessage response = client.GetAsync(url).Result;
return response.Content.ReadAsStringAsync().Result;
}
} /// <summary>
/// 发起GET异步请求
/// </summary>
/// <param name="url"></param>
/// <param name="headers"></param>
/// <param name="contentType"></param>
/// <returns></returns>
public static async Task<string> HttpGetAsync(string url, string contentType = null, Dictionary<string, string> headers = null)
{
using (HttpClient client = new HttpClient())
{
if (contentType != null)
client.DefaultRequestHeaders.Add("ContentType", contentType);
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
HttpResponseMessage response = await client.GetAsync(url);
return await response.Content.ReadAsStringAsync();
}
}
}
}
调用异步请求方法:
var result = await HttpHelper.HttpPostAsync("http://www.baidu.com/api/getuserinfo", "userid=23456798");
https://www.cnblogs.com/pudefu/p/7581956.html
https://blog.csdn.net/slowlifes/article/details/78504782
C# ASP.NET Core使用HttpClient的同步和异步请求的更多相关文章
- ASP.NET Core使用HttpClient的同步和异步请求
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.I ...
- ASIHTTPRequest系列(一):同步和异步请求
ASIHTTPRequest系列(一):同步和异步请求 发表于8个月前(2013-11-27 19:21) 阅读(431) | 评论(0) 6人收藏此文章, 我要收藏 赞0 ASIHTTPRequ ...
- 在ASP.NET Core中用HttpClient(一)——获取数据和内容
在本文中,我们将学习如何在ASP.NET Core中集成和使用HttpClient.在学习不同HttpClient功能的同时使用Web API的资源.如何从Web API获取数据,以及如何直接使用Ht ...
- 在ASP.NET Core中用HttpClient(二)——发送POST, PUT和DELETE请求
在上一篇文章中,我们已经学习了如何在ASP.NET Core中使用HttpClient从Web API获取数据.此外,我们还学习了如何使用GetAsync方法和HttpRequestMessage类发 ...
- 在ASP.NET Core中用HttpClient(三)——发送HTTP PATCH请求
在前面的两篇文章中,我们讨论了很多关于使用HttpClient进行CRUD操作的基础知识.如果你已经读过它们,你就知道如何使用HttpClient从API中获取数据,并使用HttpClient发送PO ...
- 在ASP.NET Core中用HttpClient(四)——提高性能和优化内存
到目前为止,我们一直在使用字符串创建请求体,并读取响应的内容.但是我们可以通过使用流提高性能和优化内存.因此,在本文中,我们将学习如何在请求和响应中使用HttpClient流. 什么是流 流是以文件. ...
- 在ASP.NET Core中用HttpClient(六)——ASP.NET Core中使用HttpClientFactory
到目前为止,我们一直直接使用HttpClient.在每个服务中,我们都创建了一个HttpClient实例和所有必需的配置.这会导致了重复代码.在这篇文章中,我们将学习如何通过使用HttpClient ...
- ASP.NET Core 3.x启动时运行异步任务(一)
这是一个大的题目,需要用几篇文章来说清楚.这是第一篇. 一.前言 在我们的项目中,有时候我们需要在应用程序启动前执行一些一次性的逻辑.比方说:验证配置的正确性.填充缓存.或者运行数据库清理/迁移等 ...
- Asp.Net Core IIS发布后PUT、DELETE请求错误405.0 - Method Not Allowed 因为使用了无效方法(HTTP 谓词)
一.在使用Asp.net WebAPI 或Asp.Net Core WebAPI 时 ,如果使用了Delete请求谓词,本地生产环境正常,线上发布环境报错. 服务器返回405,请求谓词无效. 二.问题 ...
随机推荐
- .net core i上 K8S(一)集群搭建
1.前言 以前搭建集群都是使用nginx反向代理,但现在我们有了更好的选择——K8S.我不打算一上来就讲K8S的知识点,因为知识点还是比较多,我打算先从搭建K8S集群讲起,我也是在搭建集群的过程中熟悉 ...
- 【QTP专题】02_时间同步点问题
一.什么是同步点 同步点是指在一个测试过程中,指示QuickTest等待应用程序中某个特定过程运行完成以后再运行下一步操作.Waits until the specified object prope ...
- Three Religions CodeForces - 1149B (字符串,dp)
大意: 给定字符串S, 要求维护三个串, 支持在每个串末尾添加或删除字符, 询问S是否能找到三个不相交的子序列等于三个串. 暴力DP, 若不考虑动态维护的话, 可以直接$O(len^3)$处理出最少需 ...
- idea debug 启动慢出现假死
断点设置不合理引发应用启动慢问题java idea应用启动很慢|非常慢|超级慢的问题排查! 解决关于应用启动超慢这个问题,其实两年前就已经遇到过,https://blog.csdn.net/li396 ...
- Ajax请求的一个重要属性contentType
比如 contentType : 'application/json;charset=UTF-8', 或者 contentType : 'text/html;charset=UTF-8', 如果不加此 ...
- Zabbix监控详解
Zabbix是什么 Zabbix 是由Alexei Vladishev创建,目前由Zabbix SIA在持续开发和支持. Zabbix 是一个企业级的分布式开源监控方案. Zabbix是一款能够监控各 ...
- 关于OC中的block自己的一些理解(二)
一.block延伸:页面间反向传值 1)first页面的代码 - (void)viewDidLoad { [super viewDidLoad]; [self setupBtn]; self.view ...
- css 移动端图片等比显示处理
第一次写博文,心情有点小小的激动~~~~~ 刚开始做移动端项目的时候遇到了一些优化的问题,比如,打开网页在2g或者3g的情况下加载网页,刚开始渲染的时候,遇到图片文件未请求,图片的高度会为0,当然,如 ...
- vue-cli起的webpack项目 用localhost可以访问,但是切换到ip就不可以访问
我用的是vux起的一个项目(移动端,基于vue的),因为是移动端的,需要在手机上测试,发现用http://localhost:8081/访问的挺好的,但是换到ip就访问不了,期初我以为是代理的原因,将 ...
- (一)使用appium之前为什么要安装nodejs???
很多人在刚接触appium自动化时,可能会像我一样,按照教程搭建好环境后,却不知道使用appium之前为什么要用到node.js,nodejs到底和appium是什么关系,对nodejs也不是很了解, ...