HttpClient 一般Http请求的简单封装

  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>
        /// 发起POST异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="httpContent"></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, HttpContent httpContent, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
        {

            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);
                }
                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, Dictionary<string, string> headers = null)
        {
            using (HttpClient client = new HttpClient())
            {
                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, Dictionary<string, string> headers = null)
        {
            using (HttpClient client = new HttpClient())
            {
                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();
            }
        }
    }

原文地址:https://www.cnblogs.com/chongyao/p/12213068.html

时间: 2024-08-01 11:05:12

HttpClient 一般Http请求的简单封装的相关文章

对系统网络请求进行简单封装

AGConnectionNet对系统网络请求进行简单封装,可便利的进行网络请求,并将数据解析与网络请求封装在同一方法下,使用更加便利(JSON 解析采用自身解析方法, XML 解析采用第三方 ReadXML 进行解析). 方法具体参数说明 初始化方法:/*** 类方法,实例化当前数据请求对象 (单例)** @return 当前请求对象*/+ (instancetype)shareRequestData; 仅进行请求数据方法/*** 请求数据 (session 请求)** @param URLSt

HttpClient 发送 HTTP、HTTPS 请求的简单封装

序 最近这几周,一直在忙同一个项目,刚开始是了解需求,需求有一定了解之后,就开始调第三方的接口.由于第三方给提供的文档很模糊,在调接口的时候,出了很多问题,一直在沟通协调,具体的无奈就不说了,由于接口的访问协议是通过 HTTP 和 HTTPS 通讯的,因此封装了一个简单的请求工具类,由于时间紧迫,并没有额外的时间对工具类进行优化和扩展,如果后续空出时间的话,我会对该工具类继续进行优化和扩展的. 引用 首先说一下该类中需要引入的 jar 包,apache 的 httpclient 包,版本号为 4

java 接口自动化测试之数据请求的简单封装

我们自己用java写接口自动化测试框架或者做个接口自动化测试平台的话,是需要自己进行相关的请求的,因此我们需要简单的封装下httpclient,我新建了一个http工具类,将get方法和post方法进行了一个简单的封装. 如果是开发的话,比如APP开发,无论是iOS还是Android,是需要将数据请求进行十分严密的封装的,因为需要对各种网络状态,请求状态做相应的判断处理,因为需要通过这些判断来做出相应的UI交互界面来给用户提示,那么我们做接口测试的话是不需要这么严密的,因为测试的前提就是要保证测

小程序wx.request请求的简单封装

1.api.js const baseUrl = 'https://api.it120.cc'; const http = ({ url = '', param = {}, ...other } = {}) => { wx.showLoading({ title: '请求中,请耐心等待..' }); let timeStart = Date.now(); return new Promise((resolve, reject) => { wx.request({ url: getUrl(url

Android简单封装类似JQuery异步请求

在android开发中经常会使用异步请求数据,通常会使用handler或者AsyncTask去做,handler 配合message 使用起来比较麻烦,AsyncTask 线程池只允许128个线程工作,会有溢出的问题,(当然一般情况不会有那么多线程同时工作的)所以写了这个代码,还望高手指正! [Java]代码 01 package com.xbl.task; 02 03 import java.io.BufferedReader; 04 import java.io.InputStream; 0

httpclient4.3简单封装

对httpclient4.3版本的一个简单封装,下面是代码 /**  * httputil工具类  *   * @author rex  */ public class HttpUtil {     private static CloseableHttpClient client;     private static BasicCookieStore cookieStore;     private static HttpGet get;     private static HttpPos

Android中网络框架的简单封装

个人博客 http://www.milovetingting.cn Android中网络框架的简单封装 前言 Android作为一款主要应用在移动终端的操作系统,访问网络是必不可少的功能.访问网络,最基本的接口有:HttpUrlConnection,HttpClient,而在后续的发展中,出现了Volley,OkHttp,Retrofit等网络封装库.由于各种原因,在实际的项目开发中,我们可能会需要在项目的版本迭代中,切换网络框架.如果对于网络框架没有好的封装,那么当需要切换网络框架时,可能就会

Android实际开发之网络请求组件的封装(OkHttp为核心)

趁周末时间撸了两天代码,将OkHttp网络请求框架进行了一次简单封装,对于实际开发非常有用.. 此次封装主要针对我们经常使用的网络请求的步骤进行封装,在已有框架OkHttp的基础上进行实际开发的封装 发送一个网络请求,有以下三个功能模块: 一:request处理 二:OkHttp核心处理 三:callback处理 我们进行网络请求组件的封装也是根据这三大模块进行封装的,下面规划一下这次封装的一个思维导图: 根据以上思维导图,我们第一步,先进行request的封装: 以下是封装的一个CommonR

android使用apache httpclient发送post请求

package com.liuc; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.ht