HTTP/HTTPS POST 请求工具类

  • Maven pom.xml 引入依赖
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.13</version>
</dependency>
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.12.0</version>
</dependency>
  • Java 工具类
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.IOException;
import java.nio.charset.StandardCharsets;/*** @author former Road* @Description HTTP request Utility* @date 2022/8/8 08:08*/
public class HttpUtils {private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);/*** Number of HTTP request retries(Please adjust by yourself)* HTTP请求重试次数(请自行调整)*/public static final int RETRY_COUNT = 3;/*** POST request with retry mechanism* 带重试机制的POST请求** @param requestBody 请求消息体* @return*/public static String doPost(String requestBody) {// Logging the request message body - 日志记录请求消息体log.info("request body:{}", requestBody);int count = 0;HttpResponse httpResponse = null;do {try {// TODO Replace with the actual request address - 替换成实际的接口请求地址httpResponse = doPost("http://127.0.0.1:8859", requestBody);} catch (Exception e) {// Recording Exception Logs - 记录异常日志log.error("Request error", e);try {// Adjust the interval between retry requests - 自行调整重试请求的间隔时间Thread.sleep(2 * 1000L);} catch (InterruptedException interruptedException) {log.error("", interruptedException);}}count++;} while (httpResponse == null && count <= RETRY_COUNT);return parseString(httpResponse);}/*** Execute the POST request* 执行POST请求** @param host 请求地址* @param body 请求消息体* @return HttpResponse* @throws Exception*/public static HttpResponse doPost(String host, String body)throws Exception {HttpClient httpClient = HttpClientBuilder.create().build();HttpPost request = new HttpPost(host);if (StringUtils.isNotBlank(body)) {request.setEntity(new StringEntity(body, StandardCharsets.UTF_8.name()));}request.setConfig(setTimeOutConfig(request.getConfig()));return httpClient.execute(request);}/*** Converts the result of the request to a string* 将结果转换成字符串** @param httpResponse http 请求响应* @return String*/public static String parseString(HttpResponse httpResponse) {if (httpResponse == null) {return null;}HttpEntity entity = httpResponse.getEntity();String resp = null;try {resp = EntityUtils.toString(entity, StandardCharsets.UTF_8.name());EntityUtils.consume(entity);} catch (IOException e) {log.error("Upstream response message error", e);}return resp;}/*** Set connection timeout, request timeout, and read timeout milliseconds* 设置 连接超时、 请求超时 、 读取超时时间  毫秒** @param requestConfig request configuration items* @return RequestConfig*/private static RequestConfig setTimeOutConfig(RequestConfig requestConfig) {if (requestConfig == null) {requestConfig = RequestConfig.DEFAULT;}return RequestConfig.copy(requestConfig).setConnectionRequestTimeout(10 * 1000).setConnectTimeout(10 * 1000).setSocketTimeout(10 * 1000).build();}}

HTTP POST 请求工具类相关推荐

  1. C#实现的UDP收发请求工具类实例

    本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSetti ...

  2. 【Java】HTTP请求工具类

    前言 在工作中可能存在要去调用其他项目的接口,这篇文章我们实现在Java代码中实现调用其他项目的接口. 本章内容: 创建一个携带参数的POST请求,去请求其他项目的接口并返回数据. 附加HTTP请求工 ...

  3. 【Http请求工具类】

    Http请求工具类(待优化) 添加相关依赖 <!-- 发送http请求依赖 --><dependency><groupId>commons-io</group ...

  4. http和https请求工具类

    https请求 @Slf4j public class HttpPostUtils {public static int RESPONSE_STATUS_OK = 0;public static JS ...

  5. Java 常用HTTP请求工具类HttpUtils

    .pom依赖 <!-- httpclient --><dependency><groupId>org.apache.httpcomponents</group ...

  6. .NET WebApi调用微信接口Https请求工具类

    .NET WebApi调用微信接口Https请求工具类 using System; using System.Collections.Generic; using System.IO; using S ...

  7. HTTP请求工具类(POST)

    HTTP请求工具类    POST请求 package com.cuierdan.utils;import org.apache.logging.log4j.LogManager; import or ...

  8. Http请求工具类:Get/Post

    第一种 import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpEntity; import org.apache.htt ...

  9. Java Https请求工具类

    个人技术网站 欢迎关注 由于微信API接口建议使用Https请求方式 而且过不久就废弃http请求方式了 所以提供以下Https工具类 public class SSLClient extends D ...

最新文章

  1. 人人都在加注芯片,英特尔却一头扎向医疗
  2. python读取txt文件写入-python 读取、写入txt文件的示例
  3. c++ list 容器
  4. 【OpenCv】Cannot parallelize deblocking type 1, decoding such frames in sequential order
  5. ubuntu-10.04硬盘安装挫折略记
  6. 遮掩java_Java×××:重载、重写、隐藏、遮蔽、遮掩(2)
  7. C/C++混淆点-strcat和strcpy区别
  8. k8s资源对象及API群组
  9. 机器学习精讲(向量逼近+函数逼近)学习笔记——第五章
  10. 谭浩强版本C语言课后习题第二章
  11. 计算机专业电路基础高考试卷,计算机专业电路基础试题(4页)-原创力文档
  12. LaTex下载与安装教程
  13. java提取富文本文字_富文本中文字部分提取
  14. 移动流量卡是月底清零吗,什么时候购买次月套餐?
  15. python substr_Python字符串的方法
  16. 高速信号线PCB走线中的阻抗匹配
  17. 写一封给36岁沈阳出生女性名字叫植瑶的人一封情书
  18. Citrix XenApp - VM Hosted Apps
  19. 产品经理基本功,如何画一个满分原型?
  20. 4. 串的【朴素模式匹配算法】、【KPM算法:求next数组、nextval数组】

热门文章

  1. 二总线-MBus讲解
  2. ubuntu20.04部署KVM环境及创建虚拟机
  3. Python入门之——pexpect模块
  4. 用聊天机器人假扮人类
  5. lua认识(lua)中的变量
  6. oracle 导出身份证号_oracle 根据身份证号计算出生日期
  7. Win11如何给应用换图标?Win11给应用换图标的方法
  8. 最新出炉,头条三面技术四面HR,看我如何一步一步攻克面试官
  9. php科研项目申报审批系统
  10. 用户增长分析——用户分群分析