引用 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的同步和异步请求的更多相关文章

  1. ASP.NET Core使用HttpClient的同步和异步请求

    using System; using System.Collections.Generic; using System.Collections.Specialized; using System.I ...

  2. ASIHTTPRequest系列(一):同步和异步请求

    ASIHTTPRequest系列(一):同步和异步请求 发表于8个月前(2013-11-27 19:21)   阅读(431) | 评论(0) 6人收藏此文章, 我要收藏 赞0 ASIHTTPRequ ...

  3. 在ASP.NET Core中用HttpClient(一)——获取数据和内容

    在本文中,我们将学习如何在ASP.NET Core中集成和使用HttpClient.在学习不同HttpClient功能的同时使用Web API的资源.如何从Web API获取数据,以及如何直接使用Ht ...

  4. 在ASP.NET Core中用HttpClient(二)——发送POST, PUT和DELETE请求

    在上一篇文章中,我们已经学习了如何在ASP.NET Core中使用HttpClient从Web API获取数据.此外,我们还学习了如何使用GetAsync方法和HttpRequestMessage类发 ...

  5. 在ASP.NET Core中用HttpClient(三)——发送HTTP PATCH请求

    在前面的两篇文章中,我们讨论了很多关于使用HttpClient进行CRUD操作的基础知识.如果你已经读过它们,你就知道如何使用HttpClient从API中获取数据,并使用HttpClient发送PO ...

  6. 在ASP.NET Core中用HttpClient(四)——提高性能和优化内存

    到目前为止,我们一直在使用字符串创建请求体,并读取响应的内容.但是我们可以通过使用流提高性能和优化内存.因此,在本文中,我们将学习如何在请求和响应中使用HttpClient流. 什么是流 流是以文件. ...

  7. 在ASP.NET Core中用HttpClient(六)——ASP.NET Core中使用HttpClientFactory

    ​到目前为止,我们一直直接使用HttpClient.在每个服务中,我们都创建了一个HttpClient实例和所有必需的配置.这会导致了重复代码.在这篇文章中,我们将学习如何通过使用HttpClient ...

  8. ASP.NET Core 3.x启动时运行异步任务(一)

    这是一个大的题目,需要用几篇文章来说清楚.这是第一篇.   一.前言 在我们的项目中,有时候我们需要在应用程序启动前执行一些一次性的逻辑.比方说:验证配置的正确性.填充缓存.或者运行数据库清理/迁移等 ...

  9. Asp.Net Core IIS发布后PUT、DELETE请求错误405.0 - Method Not Allowed 因为使用了无效方法(HTTP 谓词)

    一.在使用Asp.net WebAPI 或Asp.Net Core WebAPI 时 ,如果使用了Delete请求谓词,本地生产环境正常,线上发布环境报错. 服务器返回405,请求谓词无效. 二.问题 ...

随机推荐

  1. orcal exists

    Oracle使用了一个复杂的自平衡B-tree结构.通常,通过索引查询数据比全表扫描要快.当 Oracle找出执行查询和Update语句的最好路径时,Oracle优化器将使用索引.同样在联结多个表时使 ...

  2. 2个list取差集

    list操作 element in a list but not in other list,元素在一个list,不在另一个list 在数据量大的时候使用numpy的setdiff1d方法的性能非常好 ...

  3. [Swift]在Swift中实现自增(++)、自减(--)运算符:利用extension扩展Int类

    自增(++).自减(--)运算符主要用在For循环中,Swift有自己更简易的循环遍历方法,而且类似x- ++x这种代码不易维护. Swift为了营造自己的编码风格,树立自己的代码精神体系,已经不支持 ...

  4. NVIDIA | 一种重建照片的 AI 图像技术

    简评:或许可以称之为「擦擦乐」~ 建议大家看看视频示例 ~ 前几天,NVIDIA 的研究人员介绍了一种新的 深度学习 方法,使用该方法可以重建缺失像素的图像内容. 这种方法被称为「image inpa ...

  5. java里面的标识符、关键字和类型

    1. 注释  Java中有三种注释:   (1) // -单行注释,注释从“//”开始,终止于行尾:   (2)  -多行注释,注释从““结束:   (3)  -是Java特有的doc注释,这种注释主 ...

  6. replace函数结合正则表达式实现转化成驼峰与转化成连接字符串的方法

    //连接符转成驼峰写法 function toCamel(str){ var reg=/-(\w)/g; return str.replace(reg,function(){ return argum ...

  7. Python自动发送HTML测试报告

    在我们做自动化测试的时候,执行完所有的测试用例,我们是希望马上得到结果的,那么我们不可能一直盯着去看,这个时候就需要引入邮件功能 1.首先我们使用一个python的第三方发邮件的库 yagmail g ...

  8. POJ2259 Team Queue (JAVA)

    第一次TLE,对每个group重新设置Queue中定位,定位到每个group的最后一个元素,但WA 经过检查,DEQUEUE时没有根据情况重新计算group,插入时没有根据情况重新给last赋值 贴A ...

  9. Windows下Anaconda安装 python + tensorflow GPU版

    这里首先确认没有安装CPU版本,并默认已经安装了CUDA和Cudnn以及anaconda. 安装gpu版本的tensorflow 接下来需要安装GPU版本的tensorflow: 打开cmd并输入: ...

  10. APP元素的四大类

    一个完整的APP包括四大类:各种“栏”.内容视图.控制元素.临时视图 各种“栏”:状态栏.导航栏.标签栏.工具栏.范围栏 内容视图:列表视图.卡片式图.集合视图.图片视图.文本视图 控制元素:用于控制 ...