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,请求谓词无效. 二.问题 ...
随机推荐
- MySQL8.0本地访问设置为远程访问权限
1.登录MySQL mysql -u root -p 输入您的密码 2.选择 mysql 数据库 use mysql; 因为 mysql 数据库中存储了用户信息的 user 表. 3.在 mysql ...
- Windows 64位操作系统的ODBC
我的操作系统是windows server 2008 R2 X64,系统自带两个版本的ODBC管理器,在"运行"中输入下面内容分别调出他们: X64: C:\windows\sys ...
- “全栈2019”Java第七章:IntelliJ IDEA注释快捷键
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...
- [Objective-C语言教程]决策结构(10)
决策结构要求程序员指定一个或多个要由程序评估或测试的条件,以及在条件被确定为真时要执行的一个或多个语句,以及可选的,如果条件要执行的其他语句 被认定是假的. 以下是大多数编程语言中的典型决策结构的一般 ...
- native2ascii -- 编码转化工具
参考文档 http://blog.chinaunix.net/uid-692788-id-2681133.html 功能说明 Java 编译器和其它 Java 工具只能处理含有 Latin-1 和/或 ...
- 案例3-ubuntu和centos中自动部署tomcat相关服务的脚本
涉及redis,mysql,xtrabackup, tomcat 1. ubuntu中 #!/bin/bash #first, change to root #出错立刻中断 set -e apt-ge ...
- 北京DNS
202.106.0.20 202.106.196.115 202.106.46.151
- JavaWeb学习笔记(十五)—— 使用JDBC进行批处理
一.什么是批处理 批处理就是一批一批的处理,而不是一个一个的处理! 当你有10条SQL语句要执行时,一次向服务器发送一条SQL语句,这么做效率上很差!处理的方案是使用批处理,即一次向服务器发送多条SQ ...
- 洛谷 P5249 [LnOI2019]加特林轮盘赌 题解【概率期望】【DP】
很有意思的题目. 题目背景 加特林轮盘赌是一个养生游戏. 题目描述 与俄罗斯轮盘赌等手枪的赌博不同的是,加特林轮盘赌的赌具是加特林. 加特林轮盘赌的规则很简单:在加特林的部分弹夹中填充子弹.游戏的参加 ...
- centos文件查找命令
在使用linux时,经常需要进行文件查找.其中查找的命令主要有find和grep.两个命令是有区的. 区别:(1)find命令是根据文件的属性进行查找,如文件名,文件大小,所有者,所属组,是否为空,访 ...