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, 0, buffer.Length);
                var response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    result.msg = "错误:Respose返回不是StatusCode!=OK";
                    result.status = 500;
                    logger.Error(result.msg);
                    return result;
                }
                using (var ss = response.GetResponseStream())
                {
                    byte[] rbs = new byte[4096];
                    int count = 0;
                    string str = "";
                    while (ss != null && (count = ss.Read(rbs, 0, rbs.Length)) > 0)
                    {
                        str += Encoding.UTF8.GetString(rbs, 0, 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 = 600;
                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 = 30, 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 = 30, Dictionary<string, string> headers = null)
        {
            postData = postData ?? "";
            using (HttpClient client = new HttpClient())
            {
                client.Timeout = new TimeSpan(0, 0, 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

原文地址:https://www.cnblogs.com/love201314/p/10320763.html

时间: 2024-11-10 07:09:06

C# ASP.NET Core使用HttpClient的同步和异步请求的相关文章

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

using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace NetCoreOrder.Common { public class HttpHelper { /// <summary> /// 同步GET请求 /// </summary> /// <param name="

Asp.Net Core中HttpClient的使用方式

原文:Asp.Net Core中HttpClient的使用方式 在.Net Core应用开发中,调用第三方接口也是常有的事情,HttpClient使用人数.使用频率算是最高的一种了,在.Net Core中,HttpClient的使用方式随着版本的升级也发生了一些变化,本次就讲解一下Asp.Net Core2.1前后使用的两种方式. 一.原先HttpClient使用方式 一般来讲,喜欢要用的时候才会选择去获取资源,因此,当在有需求时才会用HttpClient去调用资源,便会使用如下这种方式或其它方

【Java&amp;Android开源库代码剖析】のandroid-async-http(如何设计一个优雅的Android网络请求框架,同时支持同步和异步请求)开篇

在<[Java&Android开源库代码剖析]のandroid-smart-image-view>一文中我们提到了android-async-http这个开源库,本文正式开篇来详细介绍这个库的实现,同时结合源码探讨如何设计一个优雅的Android网络请求框架.做过一段时间Android开发的同学应该对这个库不陌生,因为它对Apache的HttpClient API的封装使得开发者可以简洁优雅的实现网络请求和响应,并且同时支持同步和异步请求. 网络请求框架一般至少需要具备如下几个组件:1

[IOS_HTTP]NSURLConnection同步与异步请求

今天看到<WIN32多线程程序设计>的同步控制时,才发现原来自己对同步和异步的概念很模糊,甚至混淆.于是GOOGLE了一下.下面都是高人们的见解,简单明了. 同步是指:发送方发出数据后,等接收方发回响应以后才发下一个数据包的通讯方式.  异步是指:发送方发出数据后,不等接收方发回响应,接着发送下个数据包的通讯方式. 举个不太恰当的例子,就像:  SendMessage(...)  TRACE0("just  like  send");   PostMessage(...) 

关于jquery同步和异步请求问题总结

关于jquery同步和异步请求问题总结 问题 这几天做项目的时候,写脚本遇到一个问题,就是jquery异步请求和同步请求执行顺序不按代码顺序执行而是最后执行导致添加数据报错,添加到空值,这怎么忍,于是我去查找jquery api,终于知道了原来jquery默认异步请求,防止数据卡死,终于让我找到了这货 async,当async: true 时,ajax请求是异步的.当async : true 时,就是同步的,但是我又有个问题,怎么设置,这个在哪设置,用$.ajax去写这个操作,不,不太麻烦了,到

jquery 同步和异步请求

1. $.ajax 同步和异步请求 1 $.ajax({ 2 type: "POST", 3 url: "some.php", 4 async : true, // true 异步,false 同步 5 // or data:{name:"John",locationi:"Boston"} 6 data: "name=John&location=Boston", 7 success: functio

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

Web.config中的maxAllowedContentLength这个属性可以用来设置Http的Post类型请求可以提交的最大数据量,超过这个数据量的Http请求ASP.NET Core会拒绝并报错,由于ASP.NET Core的项目文件中取消了Web.config文件,所以我们无法直接在visual studio的解决方案目录中再来设置maxAllowedContentLength的属性值. 但是在发布ASP.NET Core站点后,我们会发现发布目录下有一个Web.config文件: 我

同步和异步请求

// //  ViewController.m //  UI-NO-18 // //  Created by Bruce on 15/8/13. //  Copyright (c) 2015年 Bruce. All rights reserved. // #import "ViewController.h" #import "InfoModel.h" @interface ViewController () @end @implementation ViewCont

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

一.介绍 Get和Post区别: Get是从服务器上获取数据,Post是向服务器发送数据. 对于Get方式,服务端用Request.QueryString获取变量的值,对于Post方式,服务端用Request.From获取提交的数据. Get是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内的各个字段一一对应. Post是通过HTTP Post机制,将表单内各个字段和其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址.用户看不到这个过程. Get