引用 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 IIS发布后PUT、DELETE请求错误405.0 - Method Not Allowed 因为使用了无效方法(HTTP 谓词)

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

  4. ASP.NET Core 2.0中如何更改Http请求的maxAllowedContentLength最大值

    Web.config中的maxAllowedContentLength这个属性可以用来设置Http的Post类型请求可以提交的最大数据量,超过这个数据量的Http请求ASP.NET Core会拒绝并报 ...

  5. js中同步与异步请求方式

    异步请求方式: $.ajax({ url : 'your url', data:{name:value}, cache : false, async : true, type : "POST ...

  6. Jquery的同步和异步请求

    1 异步请求:    1.1 $.ajax       $.ajax({                url : 'your url',                data:{name:valu ...

  7. Swift3.0:Get/Post同步和异步请求

    一.介绍 Get和Post区别: Get是从服务器上获取数据,Post是向服务器发送数据. 对于Get方式,服务端用Request.QueryString获取变量的值,对于Post方式,服务端用Req ...

  8. $.post 和 $.get 设置同步和异步请求

    由于$.post() 和 $.get() 默认是 异步请求,如果需要同步请求,则可以进行如下使用:在$.post()前把ajax设置为同步:$.ajaxSettings.async = false;在 ...

  9. ASIHTTP 框架,同步、 异步请求、 上传 、 下载

    ASIHTTPRequest详解 ASIHTTPRequest 是一款极其强劲的 HTTP 访问开源项目.让简单的 API 完成复杂的功能,如:异步请求,队列请求,GZIP 压缩,缓存,断点续传,进度 ...

随机推荐

  1. asp.net mvc bootstrap datatable 服务端分页

    datatable 服务端分页 因项目需求变动,需处理大量数据,更改成服务端分页,自己两天的学习笔记 先上图[ jqueryui风格] 前端代码: @{ Layout = null;} <!DO ...

  2. linux下shell脚本执行jar文件

    最近在搞一个shell脚本启动jar文件个关闭jar文件的东东.搞得我都蛋疼了.今天晚上终于弄好了 话说,小弟的linux只是刚入门,经过各方查资料终于搞定了.话不多说,下面开始上小弟写的shell脚 ...

  3. java中的注解(Annotation)

    转载:https://segmentfault.com/a/1190000007623013 简介 注解,java中提供了一种原程序中的元素关联任何信息.任何元素的途径的途径和方法. 注解是那些插入到 ...

  4. 动态规划(树形DP):HDU 5886 Tower Defence

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAA2MAAAERCAIAAAB5Jui9AAAgAElEQVR4nOy9a6wsS3YmFL/cEkh4LP

  5. Hadoop学习资料收集

    1.漫画HDFS工作原理  http://blog.csdn.net/netcoder/article/details/7442779 2.马哥教育 http://mageedu.blog.51cto ...

  6. Java良葛格 学习笔记《二》

    正则表达式 . 符合任一字符\d 符合0到9任一个数字字符\D 符合0-9以外的字符\s 符合'\t'.'\n'.'\x0B'.'\f'.'\r'等空格符\w 符合a到z.A到Z.0到9等字符,也就是 ...

  7. 201521123040《Java程序设计》第3周学习总结

    1. 本周学习总结 初学面向对象,会学习到很多碎片化的概念与知识.尝试学会使用思维导图将这些碎片化的概念.知识组织起来.请使用纸笔或者下面的工具画出本周学习到的知识点.截图或者拍照上传.参考资料:百度 ...

  8. 【HNOI2002】营业额统计

    https://www.luogu.org/problem/show?pid=2234 用Treap维护,每次查询这个数的前驱与后继哪个和它差值更小. 由于查询一个数时在Treap走出的路径必定经过它 ...

  9. C语言中的atan和atan2

    本文内容为转载,是在阅读 RTKLIB源码时意识到的这个问题,原文地址为:https://www.cnblogs.com/dutlei/archive/2013/01/14/2860332.html ...

  10. Linux deepin 中Jetbrain Idea等软件中文显示异常

    解决方案:安装常用的中文字体 # 文鼎宋体[推荐] sudo apt install fonts-arphic-uming # 文鼎楷体[推荐] sudo apt install fonts-arph ...