使用HttpClient发送post和get请求三方接口
程序员文章站
2022-05-03 17:58:36
最近在用到了HttpClient发送post和get请求三方接口的需求,所以写了个封装类方便以后用到:需要用到的一些jar的maven坐标: org.apache.httpcomponents httpclient 4.5.5&l...
最近在用到了HttpClient发送post和get请求三方接口的需求,所以写了个封装类方便以后用到:
需要用到的一些jar的maven坐标:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
HttpUtil封装类:
package com.springboot.demo.test.service;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.util.Map;
public class HttpUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
private static String chaset = "UTF-8"; // 默认编码
/**
* 发送 GET 请求(HTTP),无参数
* @param url
* @return
*/
public static String doGet(String url) {
if (StringUtils.isBlank(url)) {
return "url不能为空";
}
// 创建http GET请求
logger.info("url:{}", url);
HttpGet httpGet = new HttpGet(url);
// 设置请求和传输超时时间
httpGet.setConfig(requestConfig);
String result = "";
try (CloseableHttpClient httpclient = HttpClients.createDefault();// 创建Httpclient对象
CloseableHttpResponse response = httpclient.execute(httpGet);// 执行请求
) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), chaset);
logger.info("HttpGet方式请求成功!返回结果:{}", result);
} else {
logger.info("HttpGet方式请求失败!状态码:" + statusCode);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 发送 GET 请求(HTTP),有参数
* @param url
* @param params
* @return
*/
public static String doGet(String url, Map<String, Object> params) {
if (!CollectionUtils.isEmpty(params)) {
StringBuffer extraUrl = new StringBuffer();
int temp = 0;
for (String key : params.keySet()) {
if (temp == 0) {
extraUrl.append("?");
} else {
extraUrl.append("&");
}
extraUrl.append(key).append("=").append(params.get(key));
temp++;
}
url += extraUrl;
}
return doGet(url);
}
/**
* 发送 POST 请求(HTTP),无参数
* @param url
* @return
*/
public static String doPost(String url) {
return doPost(url, null);
}
/**
* 发送 POST 请求(HTTP),有参数
* @param url
* @return
*/
public static String doPost(String url, Map<String, Object> params) {
// 创建http POST请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
httpPost.setHeader("Content-Type", "application/json");
if (params != null) {
httpPost.setEntity(new StringEntity(JSON.toJSONString(params), ContentType.create("application/json", "utf-8")));
}
String result = "";
try (CloseableHttpClient httpclient = HttpClients.createDefault();// 创建Httpclient对象
CloseableHttpResponse response = httpclient.execute(httpPost);// 执行请求
) {
logger.info("httpPost:{}", httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), chaset);
logger.info("HttpPost方式请求成功!返回结果:{}", result);
} else {
logger.info("HttpPost方式请求失败!状态码:" + statusCode);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
用的时候直接调用就行,如:
Map<String, Object> map = new HashMap<>();
map.put("a", additionModel.getA());
map.put("b", additionModel.getB());
String result = HttpUtil.doGet("http://125.113.27.170:8080/query/v1/addition",map);
本文地址:https://blog.csdn.net/qq_33697094/article/details/110820690
推荐阅读
-
Python 使用requests模块发送GET和POST请求的实现代码
-
Android HttpClient GET或者POST请求基本使用方法
-
JAVA发送http get/post请求,调用http接口、方法详解
-
postman的安装与使用方法(模拟Get和Post请求)
-
Android HttpClient GET或者POST请求基本使用方法
-
Android下通过httpClient发送GET和POST请求的实例代码
-
postman的安装与使用方法(模拟Get和Post请求)
-
使用PHP Socket 编程模拟Http post和get请求
-
微信小程序授权 获取用户的openid和session_key【后端使用java语言编写】,我写的是get方式,目的是测试能否获取到微信服务器中的数据,后期我会写上post请求方式。
-
PHP get和post向服务器发送请求