.net post Get请求自己封装的一些方法 支持多种格式参数

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace EmailHelp.Utility
{
    public class HttpClientHelper
    {
        #region Get请求
        /// <summary>
        /// get请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool GetResponse(string url, out string statusCode, string ContentType = "application/json")
        {
            if (url.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            HttpClient httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Accept.Add(
               new MediaTypeWithQualityHeaderValue(ContentType)
               );

            HttpResponseMessage response = httpClient.GetAsync(url).Result;


            if (response.IsSuccessStatusCode)
            {
                statusCode = response.Content.ReadAsStringAsync().Result;
            }
            else
            {
                statusCode = "";
            }

            return response.IsSuccessStatusCode;
        }

        public static bool GetResponse<T>(string url, out T statusCode, string ContentType = "application/json")
            where T : class, new()
        {
            if (url.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            HttpClient httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Accept.Add(
               new MediaTypeWithQualityHeaderValue(ContentType)
               );

            HttpResponseMessage response = httpClient.GetAsync(url).Result;

            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                string s = t.Result;

                statusCode = JsonConvert.DeserializeObject<T>(s);
            }
            else
            {
                statusCode = null;
            }
            return response.IsSuccessStatusCode;
        }
        #endregion

        #region Post请求
        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="postData">请求数据(已转为Json数据)</param>
        /// <param name="statusCode">返回数据</param>
        /// <param name="ContentType">请求类型</param>
        /// <param name="CodingFormat">编码格式</param>
        /// <returns>请求结果</returns>
        public static bool PostResponseJson(string url, string postData, out string statusCode, string ContentType = "application/json", string CodingFormat = "utf-8")
        {
            if (url.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            HttpContent httpContent = new StringContent(postData);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue(ContentType);
            httpContent.Headers.ContentType.CharSet = CodingFormat;

            HttpClientHandler handler = new HttpClientHandler();
            handler.UseProxy = false;//不加这个会非常慢

            HttpClient httpClient = new HttpClient(handler);

            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

            statusCode = response.StatusCode.ToString();

            if (response.IsSuccessStatusCode)
            {
                statusCode = response.Content.ReadAsStringAsync().Result;
            }
            else
            {
                statusCode = "";
            }
            return response.IsSuccessStatusCode;
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="postData">请求数据</param>
        /// <param name="statusCode">返回数据</param>
        /// <param name="ContentType">请求类型</param>
        /// <param name="CodingFormat">编码格式</param>
        /// <returns>请求结果</returns>
        public static bool PostResponse(string url, string postData, out string statusCode, string ContentType = "application/json", string CodingFormat = "utf-8")
        {
            if (url.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            // 对象数据转为Json数据                       
            JsonSerializerSettings jsetting = new JsonSerializerSettings();
            jsetting.NullValueHandling = NullValueHandling.Ignore;
            postData = JsonConvert.SerializeObject(postData, jsetting);

            HttpContent httpContent = new StringContent(postData);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue(ContentType);
            httpContent.Headers.ContentType.CharSet = CodingFormat;

            HttpClientHandler handler = new HttpClientHandler();
            handler.UseProxy = false;//不加这个会非常慢

            HttpClient httpClient = new HttpClient(handler);

            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

            statusCode = response.StatusCode.ToString();

            if (response.IsSuccessStatusCode)
            {
                statusCode = response.Content.ReadAsStringAsync().Result;
            }
            else
            {
                statusCode = "";
            }
            return response.IsSuccessStatusCode;
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="postData">请求数据</param>
        /// <param name="statusCode">返回数据</param>
        /// <param name="ContentType">请求类型</param>
        /// <param name="CodingFormat">编码格式</param>
        /// <returns>请求结果</returns>
        public static bool PostResponse(string url, string postData, out dynamic statusCode, string ContentType = "application/json", string CodingFormat = "utf-8")
        {
            if (url.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            // 对象数据转为Json数据
            JsonSerializerSettings jsetting = new JsonSerializerSettings();
            jsetting.NullValueHandling = NullValueHandling.Ignore;

            string jsondata = JsonConvert.SerializeObject(postData, jsetting);

            HttpContent httpContent = new StringContent(jsondata);

            httpContent.Headers.ContentType = new MediaTypeHeaderValue(ContentType);
            httpContent.Headers.ContentType.CharSet = CodingFormat;

            HttpClientHandler handler = new HttpClientHandler();
            handler.UseProxy = false;//不加这个会非常慢
            HttpClient httpClient = new HttpClient(handler);

            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                string s = t.Result;

                statusCode = JsonConvert.DeserializeObject<dynamic>(s);
            }
            else
            {
                statusCode = null;
            }

            return response.IsSuccessStatusCode;
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <typeparam name="T">返回对象</typeparam>
        /// <param name="url">请求地址</param>
        /// <param name="postData">请求数据</param>
        /// <param name="statusCode">返回数据</param>
        /// <param name="ContentType">请求类型</param>
        /// <param name="CodingFormat">编码格式</param>
        /// <returns>请求结果</returns>
        public static bool PostResponse<T>(string url, string postData, out T statusCode, string ContentType = "application/json", string CodingFormat = "utf-8")
            where T : class, new()
        {
            if (url.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            // 对象数据转为Json数据
            JsonSerializerSettings jsetting = new JsonSerializerSettings();
            jsetting.NullValueHandling = NullValueHandling.Ignore;

            string jsondata = JsonConvert.SerializeObject(postData, jsetting);

            HttpContent httpContent = new StringContent(jsondata);

            httpContent.Headers.ContentType = new MediaTypeHeaderValue(ContentType);
            httpContent.Headers.ContentType.CharSet = CodingFormat;

            HttpClientHandler handler = new HttpClientHandler();
            handler.UseProxy = false;//不加这个会非常慢
            HttpClient httpClient = new HttpClient(handler);

            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                string s = t.Result;
                statusCode = JsonConvert.DeserializeObject<T>(s);
            }
            else
            {
                statusCode = null;
            }

            return response.IsSuccessStatusCode;
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <typeparam name="T">返回对象</typeparam>
        /// <param name="url">请求地址</param>
        /// <param name="postData">请求数据</param>
        /// <param name="statusCode">返回数据</param>
        /// <param name="ContentType">请求类型</param>
        /// <param name="CodingFormat">编码格式</param>
        /// <returns>请求结果</returns>
        public static bool PostResponse<T>(string url, T postData, out string statusCode, string ContentType = "application/json", string CodingFormat = "utf-8")
            where T : class, new()
        {
            return PostResponse<T, string>(url, postData, out statusCode, ContentType, CodingFormat);
        }

        /// <summary>
        /// 发送Post请求
        /// </summary>
        /// <typeparam name="T">请求对象</typeparam>
        /// <typeparam name="T1">返回对象</typeparam>
        /// <param name="url">请求地址</param>
        /// <param name="postData">请求数据</param>
        /// <param name="statusCode">返回数据</param>
        /// <param name="ContentType">请求类型</param>
        /// <param name="CodingFormat">编码格式</param>
        /// <returns>请求结果</returns>
        public static bool PostResponse<T, T1>(string url, T postData, out T1 statusCode, string ContentType = "application/json", string CodingFormat = "utf-8")
            where T : class, new()
        {
            if (url.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            // 对象数据转为Json数据
            JsonSerializerSettings jsetting = new JsonSerializerSettings();
            jsetting.NullValueHandling = NullValueHandling.Ignore;

            string jsondata = JsonConvert.SerializeObject(postData, jsetting);

            HttpContent httpContent = new StringContent(jsondata);

            httpContent.Headers.ContentType = new MediaTypeHeaderValue(ContentType);
            httpContent.Headers.ContentType.CharSet = CodingFormat;

            HttpClientHandler handler = new HttpClientHandler();
            handler.UseProxy = false;//不加这个会非常慢
            HttpClient httpClient = new HttpClient(handler);

            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                string s = t.Result;

                statusCode = JsonConvert.DeserializeObject<T1>(s);
            }
            else
            {
                statusCode = default(T1);
            }

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("请求失败。" + jsondata);
            }

            return response.IsSuccessStatusCode;
        }

        /// <summary>
        /// 发送Post请求
        /// </summary>
        /// <typeparam name="T">请求对象</typeparam>
        /// <typeparam name="T1">返回对象</typeparam>
        /// <param name="url">请求地址</param>
        /// <param name="postData">请求数据</param>
        /// <param name="statusCode">返回数据</param>
        /// <param name="ContentType">请求类型</param>
        /// <param name="CodingFormat">编码格式</param>
        /// <returns>请求结果</returns>
        /// <returns></returns>
        public static bool PostResponse<T, T1>(string url, T postData, out List<T1> statusCode, string ContentType = "application/json", string CodingFormat = "utf-8")
            where T : class, new()
        {
            if (url.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            // 对象数据转为Json数据
            JsonSerializerSettings jsetting = new JsonSerializerSettings();
            jsetting.NullValueHandling = NullValueHandling.Ignore;

            string jsondata = JsonConvert.SerializeObject(postData, jsetting);

            HttpContent httpContent = new StringContent(jsondata);

            httpContent.Headers.ContentType = new MediaTypeHeaderValue(ContentType);
            httpContent.Headers.ContentType.CharSet = CodingFormat;

            HttpClientHandler handler = new HttpClientHandler();
            handler.UseProxy = false;//不加这个会非常慢
            HttpClient httpClient = new HttpClient(handler);

            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                string s = t.Result;

                statusCode = JsonConvert.DeserializeObject<List<T1>>(s);
            }
            else
            {
                statusCode = default(List<T1>);
            }

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("请求失败。" + jsondata);
            }

            return response.IsSuccessStatusCode;
        }

        #endregion

        /// <summary>
        /// V3接口全部为Xml形式,故有此方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="xmlString"></param>
        /// <returns></returns>
        public static bool PostXmlResponse<T>(string url, string xmlString, out T statusCode, string ContentType = "application/json", string CodingFormat = "utf-8")
            where T : class, new()
        {
            if (url.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            HttpContent httpContent = new StringContent(xmlString);

            httpContent.Headers.ContentType = new MediaTypeHeaderValue(ContentType);
            httpContent.Headers.ContentType.CharSet = CodingFormat;

            HttpClientHandler handler = new HttpClientHandler();
            handler.UseProxy = false;//不加这个会非常慢
            HttpClient httpClient = new HttpClient(handler);

            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                string s = t.Result;

                statusCode = XmlDeserialize<T>(s);
            }
            else
            {
                statusCode = null;
            }

            return response.IsSuccessStatusCode;
        }

        /// <summary>
        /// 反序列化Xml
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xmlString"></param>
        /// <returns></returns>
        public static T XmlDeserialize<T>(string xmlString)
            where T : class, new()
        {
            try
            {
                XmlSerializer ser = new XmlSerializer(typeof(T));
                using (StringReader reader = new StringReader(xmlString))
                {
                    return (T)ser.Deserialize(reader);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("XmlDeserialize发生异常:xmlString:" + xmlString + "异常信息:" + ex.Message);
            }
        }

    }
}

整个代码都在这了!有需要的直接拿走就行了!多个方法重载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是使用HttpClient5发送POSTGET请求的Java代码示例: ```java import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.io.entity.StringEntity; import java.io.IOException; import java.net.URI; public class HttpClientUtils { /** * 发送GET请求 * * @param url 请求的URL * @return 响应字符串 * @throws IOException */ public static String sendGetRequest(String url) throws IOException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpGet httpGet = new HttpGet(url); ClassicHttpResponse response = httpClient.execute(httpGet); return response.getEntity().toString(); } } /** * 发送POST请求 * * @param url 请求的URL * @param params 请求参数(JSON格式) * @return 响应字符串 * @throws IOException */ public static String sendPostRequest(String url, String params) throws IOException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(URI.create(url)); StringEntity requestEntity = new StringEntity(params, ContentType.APPLICATION_JSON); httpPost.setEntity(requestEntity); ClassicHttpResponse response = httpClient.execute(httpPost); return response.getEntity().toString(); } } } ``` 这里我们使用了Apache HttpClient5库来发送请求,通过封装方法,可以方便地在其他地方调用。注意,在使用完CloseableHttpClient后,一定要关闭它,否则可能会导致连接泄露和资源浪费。在上面的示例中,我们使用了try-with-resources语法糖来自动关闭CloseableHttpClient。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值