作者在工作中,遇到一些需要调用三方接口的任务,就需要用到 HTTP 调用工具。这里,我总结了一下 实现 HTTP 调用的方式,共有 7 种(后续会继续新增),分别如下:
HttpClient
OkHttp
OKHttpUtil
Jodd HTTP
Hutool HTTP
RestTemplate
forest
1. HttpClient
dependency>
groupId>org.apache.httpcomponentsgroupId>
artifactId>httpclientartifactId>
version>4.5.6version>
dependency>
public class HttpClientUtil {
public static String get(String url, MapString, String> urlParam, MapString, String> header, boolean ssl) {
return get(url, urlParam, header, CharEncoding.UTF_8, ssl);
}
public static String get(String url, MapString, String> urlParams, MapString, String> headers, String charSet, boolean ssl) {
HttpGet httpGet = new HttpGet(charSet == null ? addParams(url, urlParams) : addParamsWithCharSet(url, urlParams, charSet));
return getResponse(httpGet, charSet, headers, ssl);
}
// 以请求体JSON发送数据
public static String postJson(String url, MapString, String> urlParams, MapString, String> headers, String data, boolean ssl) {
HttpPost httpPost = new HttpPost(addParams(url, urlParams));
httpPost.setEntity(new StringEntity(data, ContentType.APPLICATION_JSON));
return getResponse(httpPost, CharEncoding.UTF_8, headers, ssl);
}
// 以表单的形式发送数据
public static String postForm(String url, MapString, String> urlParams, MapString, String> headers, MapString, String> data, boolean ssl) {
HttpPost httpPost = new HttpPost(addParams(url, urlParams));
ContentType contentType = ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8);
if (Objects.isNull(headers)) {
headers = new HashMap>();
}
headers.put("Content-Type", contentType.toString());
ListNameValuePair> list = new ArrayList>();
for (Map.EntryString, String> entry : data.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
if (list.size() > 0) {
UrlEncodedFormEntity entity = null;
try {
entity = new UrlEncodedFormEntity(list, CharEncoding.UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
httpPost.setEntity(entity);
}
return getResponse(httpPost, CharEncoding.UTF_8, headers, ssl);
}
// 获取响应数据
private static String getResponse(HttpRequestBase httpRequestBase, String charSet, MapString, String> headers, boolean ssl) {
CloseableHttpClient httpClient = null;
try {
httpClient = ssl ? getHttpClient() : HttpClients.createDefault();
httpRequestBase.setConfig(getRequestConfig());
if (headers.size() > 0) {
httpRequestBase.setHeaders(getHeaders(headers));
}
CloseableHttpResponse response = httpClient.execute(httpRequestBase);
int statusCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == statusCode) {
HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity, charSet);
EntityUtils.consume(entity);
return res;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (Objects.nonNull(httpClient)) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
throw new RuntimeException("调用失败");
}
private static RequestConfig getRequestConfig() {
return RequestConfig.custom().setConnectTimeout(6000 * 2).setConnectionRequestTimeout(6000 * 2).setSocketTimeout(6000 * 2).build();
}
private static String addParams(String url, MapString, String> params) {
return addParamsWithCharSet(url, params, CharEncoding.UTF_8);
}
private static String addParamsWithCharSet(String url, MapString, String> params, String charSet) {
if (params == null || params.isEmpty()) {
return url;
}
StringBuilder sb = new StringBuilder();
try {
for (Map.EntryString, String> entry : params.entrySet()) {
sb.append("&").append(entry.getKey()).append("=");
sb.append(charSet == null ? entry.getValue() : URLEncoder.encode(entry.getValue(), charSet));
}
if (!url.contains("?")) {
sb.deleteCharAt(0).insert(0, "?");
}
} catch (Exception e) {
e.printStackTrace();
}
return url + sb;
}
// HTTPS client 创建
public static CloseableHttpClient getHttpClient() {
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext context = null;
try {
context = SSLContext.getInstance("SSL");
context.init(null, new TrustManager[]{trustManager}, null);
return HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(context)).build();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
// 设置请求头
private static Header[] getHeaders(MapString, String> header) {
if (header.size() == 0) {
return new Header[]{};
}
ListHeader> headers = new ArrayList>();
for (String key : header.keySet()) {
headers.add(new BasicHeader(key, header.get(key)));
}
return headers.toArray(new Header[]{});
}
}
使用:
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/queryById")
public String queryById(String id) {
MapString, String> params = new HashMap>();
MapString, String> headers = new HashMap>();
params.put("id", id);
headers.put("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODcxNjM4MDcsInVzZXJuYW1lIjoibGlqaW5nIn0.BUeqjiBQrH0DCfciRQsWo1P1XOoIxXNuNaM27vjAmys");
String url = "http://localhost:20001/test/queryById";
return HttpClientUtil.get(url, params, headers, false);
}
@PostMapping("/add")
public String add() {
MapString, String> headers = new HashMap>();
headers.put("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODcxNjM4MDcsInVzZXJuYW1lIjoibGlqaW5nIn0.BUeqjiBQrH0DCfciRQsWo1P1XOoIxXNuNaM27vjAmys");
UserVo userVo = new UserVo();
userVo.setId(1L);
userVo.setName("zzc");
String url = "http://localhost:20001/test/add";
return HttpClientUtil.postJson(url, null, headers, JSON.toJSONString(userVo),false);
}
}
2.OkHttp
dependency>
groupId>com.squareup.okhttp3groupId>
artifactId>okhttpartifactId>
version>3.14.7version>
dependency>
public class OkHttpUtil {
private static volatile OkHttpClient okHttpClient = null;
private static volatile Semaphore semaphore = null;
private MapString, String> headerMap;
private MapString, Object> paramMap;
private String url;
private Request.Builder request;
private String body;
private OkHttpUtil() {
if (Objects.isNull(okHttpClient)) {
synchronized (OkHttpUtil.class) {
if (Objects.isNull(okHttpClient)) {
TrustManager[] trustManagers = buildTrustManager();
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.sslSocketFactory(createSSLSocketFactory(trustManagers), (X509TrustManager)trustManagers[0])
.hostnameVerifier((hostname, session) -> true)
.retryOnConnectionFailure(true)
.build();
addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36");
}
}
}
}
public OkHttpUtil initGet() {
request = new Request.Builder().get();
StringBuilder builder = new StringBuilder(url);
if (Objects.nonNull(paramMap)) {
builder.append("?");
paramMap.forEach((key, value) -> {
try {
builder.append(URLEncoder.encode(key, "utf-8"))
.append("=")
.append(URLEncoder.encode((String)value, "utf-8"))
.append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
});
builder.deleteCharAt(builder.length() - 1);
}
request.url(builder.toString());
return this;
}
public OkHttpUtil initPost(boolean isJson) {
RequestBody requestBody = null;
if (isJson) {
requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body);
} else {
FormBody.Builder formBody = new FormBody.Builder();
if (Objects.nonNull(paramMap)) {
paramMap.forEach((x, y) -> formBody.add(x, (String) y));
}
requestBody = formBody.build();
}
request = new Request.Builder().post(requestBody).url(url);
return this;
}
/**
* @Description:同步请求
* @Author: zzc
* @Date: 2022-12-04 18:06
* @return: java.lang.String
**/
public String sync() {
setHeader(request);
try {
Response result = okHttpClient.newCall(request.build()).execute();
if (Objects.nonNull(result)) {
return result.body().string();
}
} catch (IOException e) {
e.printStackTrace();
}
return "请求失败";
}
/**
* @Description:异步请求,有返回值
* @Author: zzc
* @Date: 2022-12-04 18:05
* @return: java.lang.String
**/
public String async() {
StringBuffer buffer = new StringBuffer();
setHeader(request);
okHttpClient.newCall(request.build()).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
buffer.append("请求出错").append(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (Objects.nonNull(response.body())) {
buffer.append(response.body().string());
getSemaphore().release();
}
}
});
try {
getSemaphore().acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
return buffer.toString();
}
private static Semaphore getSemaphore() {
synchronized (OkHttpUtil.class) {
if (Objects.isNull(semaphore)) {
semaphore = new Semaphore(0);
}
}
return semaphore;
}
public static OkHttpUtil builder() {
return new OkHttpUtil();
}
public OkHttpUtil url(String url) {
this.url = url;
return this;
}
public OkHttpUtil addParam(String key, String value) {
if (Objects.isNull(paramMap)) {
paramMap = new LinkedHashMap>(16);
}
paramMap.put(key, value);
return this;
}
public OkHttpUtil addBody(String body) {
this.body = body;
return this;
}
public void setHeader(Request.Builder request) {
if (Objects.nonNull(headerMap)) {
headerMap.forEach(request::addHeader);
}
}
public OkHttpUtil addHeader(String key, String value) {
if (Objects.isNull(headerMap)) {
headerMap = new LinkedHashMap>(16);
}
headerMap.put(key, value);
return this;
}
/**
* @Description:生成安全套接字工厂,用于Https请求的证书跳过
* @Author: zzc
* @Date: 2022-11-30 16:03
* @param trustManagers:
* @return: javax.net.ssl.SSLSocketFactory
**/
private static SSLSocketFactory createSSLSocketFactory(TrustManager[] trustManagers) {
SSLSocketFactory sslSocketFactory = null;
try {
SSLContext ssl = SSLContext.getInstance("SSL");
ssl.init(null, trustManagers, new SecureRandom());
sslSocketFactory = ssl.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
return sslSocketFactory;
}
private static TrustManager[] buildTrustManager() {
return new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
};
}
}
public interface ICallback {
void onSuccess(Call call, String data);
void onFail(Call call, String errorMsg);
}
使用:
@RestController
@RequestMapping("/ok")
public class OkHttpController {
@GetMapping("/getByNoParams")
public String getByNoParams() {
String result = OkHttpUtil.builder().url("http://localhost:8080/http/listUsers")
.initGet()
.sync();
System.out.println(result);
return "get";
}
@GetMapping("/get")
public String get() {
String result = OkHttpUtil.builder().url("http://localhost:8080/http/getUserById")
.addParam("id", "1")
.initGet()
.sync();
System.out.println(result);
return "get";
}
@GetMapping("/postByNoParams")
public String postByNoParams() {
String result = OkHttpUtil.builder().url("http://localhost:8080/http/listUserList")
.initPost(false)
.sync();
System.out.println(result);
return "post";
}
@GetMapping("/post")
public String post() {
String result = OkHttpUtil.builder().url("http://localhost:8080/http/getUserVoById")
.addParam("id", "1")
//.addHeader()
.initPost(false)
.sync();
System.out.println(result);
return "post";
}
}
3.OKHttpUtil
在 Java 的世界中,Http 客户端之前一直是 Apache 家的 HttpClient
占据主导,但是由于此包较为庞大,API 又比较难用,因此并不使用很多场景。而新兴的 OkHttp
、Jodd-http
固然好用,但是面对一些场景时,学习成本还是有一些的。针对 OKHttp
,OkHttpUtil
做了一层封装,使 Http 请求变得无比简单。
dependency>
groupId>io.github.admin4jgroupId>
artifactId>httpartifactId>
version>0.4.0version>
dependency>
public class OkHttpUtil {
public static JSONObject get(String url, MapString, Object> queryParams) throws IOException {
Response response = HttpUtil.get(url, queryParams);
return JSONObject.parseObject(response.body().string());
}
public static JSONObject get(String url, MapString, Object> queryParams, MapString, Object> headers) throws IOException {
HttpRequest httpRequest = HttpRequest.get(url);
setParams(queryParams, httpRequest);
Response response = httpRequest.queryParams().headers(headers).execute();
return JSONObject.parseObject(response.body().string());
}
public static JSONObject post(String url, String json) throws IOException {
Response response = HttpUtil.post(url, json);
assert response.body() != null;
return JSONObject.parseObject(response.body().string());
}
public static JSONObject postForm(String url, MapString, Object> formParams) throws IOException {
Response response = HttpUtil.postForm(url, formParams);
assert response.body() != null;
return JSONObject.parseObject(response.body().string());
}
public static JSONObject post(String url, String json, MapString, Object> headers) throws IOException {
HttpRequest httpRequest = HttpRequest.post(url);
httpRequest.setBody(json);
Response response = httpRequest.headers(headers).execute();
return JSONObject.parseObject(response.body().string());
}
private static void setParams(MapString, Object> queryParams, HttpRequest httpRequest) {
ListPair> pairs = new ArrayList>(queryParams.size());
queryParams.forEach((x, y) -> pairs.add(Pair.of(x, y)));
if (pairs.size() > 0) {
pairs.forEach(httpRequest::queryParams);
}
}
private static JSONObject upload() throws IOException {
File file = new File("C:\Users\andanyang\Downloads\Sql.txt");
MapString, Object> formParams = new HashMap>();
formParams.put("key", "test");
formParams.put("file", file);
formParams.put("token", "WXyUseb-D4sCum-EvTIDYL-mEehwDtrSBg-Zca7t:qgOcR2gUoKmxt-VnsNb657Oatzo=:eyJzY29wZSI6InpoYW56aGkiLCJkZWFkbGluZSI6MTY2NTMwNzUxNH0=");
Response response = HttpUtil.upload("https://upload.qiniup.com/", formParams);
return JSONObject.parseObject(response.body().string());
}
private static void download() throws IOException {
HttpUtil.down("https://gitee.com/admin4j/common-http","path/");
}
}
使用:
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/queryById")
public String queryById(String id) throws IOException {
MapString, Object> params = new HashMap>();
MapString, Object> headers = new HashMap>();
params.put("id", id);
headers.put("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODcyMjgxNjUsInVzZXJuYW1lIjoibGlqaW5nIn0.QNlQVrqiQymaeX38VXJCYhBXf3W6nQVDTmvlF0QKK-k");
String url = "http://localhost:20001/test/queryById";
OkHttpUtil.get(url, params, headers);
return "get";
}
@PostMapping("/add")
public String add() throws IOException {
MapString, String> headers = new HashMap>();
headers.put("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODcxNjM4MDcsInVzZXJuYW1lIjoibGlqaW5nIn0.BUeqjiBQrH0DCfciRQsWo1P1XOoIxXNuNaM27vjAmys");
UserVo userVo = new UserVo();
userVo.setId(1L);
userVo.setName("zzc");
String url = "http://localhost:20001/test/add";
OkHttpUtil.post(url, JSON.toJSONString(userVo));
return "post";
}
@PostMapping("/add2")
public String add2() throws IOException {
MapString, Object> headers = new HashMap>();
headers.put("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODcyMzUzOTksInVzZXJuYW1lIjoibGlqaW5nIn0.zTOOhKS13RqWPj01fhWZoWR1Qz055uv2XG_eSIdt1NE");
UserVo userVo = new UserVo();
userVo.setId(1L);
userVo.setName("zzc");
String url = "http://localhost:20001/test/add";
OkHttpUtil.post(url, JSON.toJSONString(userVo), headers);
return "post";
}
}
4.Jodd HTTP
dependency>
groupId>org.joddgroupId>
artifactId>jodd-httpartifactId>
version>6.3.0version>
dependency>
public class JoddUtil {
public static JSONObject get(String url, MapString, Object> queryParams) throws IOException {
return get(url, queryParams, null);
}
public static JSONObject get(String url, MapString, Object> queryParams, MapString, String> headers) throws IOException {
HttpRequest request = HttpRequest.get(url);
setParams(request, queryParams);
setHeaders(request, headers);
return getResponse(request);
}
public static JSONObject post(String url, String json) throws IOException {
return post(url, json, null);
}
public static JSONObject post(String url, String json, MapString, String> headers) throws IOException {
HttpRequest request = HttpRequest.post(url);
request.contentType("application/json");
request.charset("utf-8");
setHeaders(request, headers);
request.body(json);
return getResponse(request);
}
public static JSONObject postForm(String url, MapString, Object> formParams) throws IOException {
return postForm(url, formParams, null);
}
public static JSONObject postForm(String url, MapString, Object> formParams, MapString, String> headers) throws IOException {
HttpRequest request = HttpRequest.post(url);
request.form(formParams);
setHeaders(request, headers);
return getResponse(request);
}
private static JSONObject getResponse(HttpRequest request) {
HttpResponse response = request.send();
response.charset("UTF-8");
return JSONObject.parseObject(response.bodyText());
}
private static void setParams(HttpRequest request, MapString, Object> queryParams) {
if (Objects.nonNull(queryParams) && queryParams.size() > 0) {
queryParams.forEach(request::query);
}
}
private static void setHeaders(HttpRequest request, MapString, String> headers) {
if (Objects.nonNull(headers) && headers.size() > 0) {
request.header(headers);
}
}
}
使用:
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/queryById")
public String queryById(String id) throws IOException {
MapString, Object> params = new HashMap>();
MapString, String> headers = new HashMap>();
params.put("id", id);
headers.put("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODcyNDQ2MjQsInVzZXJuYW1lIjoibGlqaW5nIn0.adNXSJnLDXBIRzcykM2Pkh1CF3R0So6D8FZ6w18PuXs");
String url = "http://localhost:20001/test/queryById";
JSONObject jsonObject = JoddUtil.get(url, params, headers);
return "get";
}
@PostMapping("/add")
public String add() throws IOException {
MapString, String> headers = new HashMap>();
headers.put("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODcyNDQ2MjQsInVzZXJuYW1lIjoibGlqaW5nIn0.adNXSJnLDXBIRzcykM2Pkh1CF3R0So6D8FZ6w18PuXs");
UserVo userVo = new UserVo();
userVo.setId(1L);
userVo.setName("zzc");
String url = "http://localhost:20001/test/add";
JSONObject jsonObject = JoddUtil.post(url, JSON.toJSONString(userVo), headers);
return "post";
}
@PostMapping("/add2")
public String add2() throws IOException {
MapString, String> headers = new HashMap>();
MapString, Object> formParams = new HashMap>();
headers.put("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODcyNDQ2MjQsInVzZXJuYW1lIjoibGlqaW5nIn0.adNXSJnLDXBIRzcykM2Pkh1CF3R0So6D8FZ6w18PuXs");
formParams.put("id", 1631112733290594305L);
String url = "http://localhost:20001/test/add2";
JSONObject jsonObject = JoddUtil.postForm(url, formParams, headers);
return "post";
}
}
5.Hutool HTTP
Http客户端工具类-HttpUtil
dependency>
groupId>cn.hutoolgroupId>
artifactId>hutool-allartifactId>
version>5.8.6version>
dependency>
public class HutoolHttpUtil {
public static JSONObject get(String url, MapString, Object> queryParams) throws IOException {
return get(url, queryParams, new HashMap>(1));
}
public static JSONObject get(String url, MapString, Object> queryParams, MapString, String> headers) throws IOException {
String body = HttpRequest.get(url).form(queryParams).addHeaders(headers).execute().body();
return JSONObject.parseObject(body);
}
public static JSONObject post(String url, String json, MapString, String> headers) {
String body = HttpRequest.post(url).body(json).addHeaders(headers).execute().body();
return JSONObject.parseObject(body);
}
}
6.RestTemplate
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
@Component
public class RestTemplateUtil {
@Autowired
private RestTemplate restTemplate;
public JSONObject get(String url, MapString, Object> queryParams) throws IOException {
return get(url, queryParams, new HashMap>(1));
}
public JSONObject get(String url, MapString, Object> queryParams, MapString, String> headerParams) throws IOException {
String tempUrl = setParamsByAppendUrl(queryParams, url);
HttpHeaders headers = new HttpHeaders();
headerParams.forEach(headers::add);
HttpEntityMultiValueMapString, Object>> httpEntity = new HttpEntity>(null, headers);
ResponseEntityString> response = restTemplate.exchange(tempUrl, HttpMethod.GET, httpEntity, String.class);
return JSONObject.parseObject(response.getBody());
}
public JSONObject get2(String url, MapString, Object> queryParams, MapString, String> headerParams) throws IOException {
String tempUrl = setParamsByPath(queryParams, url);
HttpHeaders headers = new HttpHeaders();
headerParams.forEach(headers::add);
HttpEntityMultiValueMapString, Object>> httpEntity = new HttpEntity>(null, headers);
ResponseEntityString> response = restTemplate.exchange(tempUrl, HttpMethod.GET, httpEntity, String.class, queryParams);
return JSONObject.parseObject(response.getBody());
}
public JSONObject post(String url, String json, MapString, String> headerParams) {
HttpHeaders headers = new HttpHeaders();
headerParams.forEach(headers::add);
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
HttpEntityString> httpEntity = new HttpEntity>(json, headers);
ResponseEntityString> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
return JSONObject.parseObject(response.getBody());
}
private String setParamsByPath(MapString, Object> queryParams, String url) {
// url?id={id}&name={name}
if (queryParams == null || queryParams.isEmpty()) {
return url;
}
StringBuilder sb = new StringBuilder();
try {
for (Map.EntryString, Object> entry : queryParams.entrySet()) {
sb.append("&").append(entry.getKey()).append("=").append("{").append(entry.getKey()).append("}");
}
if (!url.contains("?")) {
sb.deleteCharAt(0).insert(0, "?");
}
} catch (Exception e) {
e.printStackTrace();
}
return url + sb;
}
private String setParamsByAppendUrl(MapString, Object> queryParams, String url) {
// url?id=1&name=zzc
if (queryParams == null || queryParams.isEmpty()) {
return url;
}
StringBuilder sb = new StringBuilder();
try {
for (Map.EntryString, Object> entry : queryParams.entrySet()) {
sb.append("&").append(entry.getKey()).append("=");
sb.append(entry.getValue());
}
if (!url.contains("?")) {
sb.deleteCharAt(0).insert(0, "?");
}
} catch (Exception e) {
e.printStackTrace();
}
return url + sb;
}
}
使用:
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private RestTemplateUtil restTemplateUtil;
@GetMapping("/queryById")
public String queryById(String id) throws IOException {
MapString, Object> params = new HashMap>();
MapString, String> headers = new HashMap>();
params.put("id", id);
headers.put("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODczMTMxNTMsInVzZXJuYW1lIjoibGlqaW5nIn0.DStv6J23FcHRAWO5kvorfVHbao7Sih4nHPU-k4ynmeM");
String url = "http://localhost:20001/test/queryById";
JSONObject jsonObject = restTemplateUtil.get2(url, params, headers);
return "get";
}
@PostMapping("/add")
public String add() throws IOException {
MapString, String> headers = new HashMap>();
headers.put("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODczMTMxNTMsInVzZXJuYW1lIjoibGlqaW5nIn0.DStv6J23FcHRAWO5kvorfVHbao7Sih4nHPU-k4ynmeM");
UserVo userVo = new UserVo();
userVo.setId(1L);
userVo.setName("zzc");
String url = "http://localhost:20001/test/add";
JSONObject jsonObject = restTemplateUtil.post(url, JSON.toJSONString(userVo), headers);
return "post";
}
}
7.forest
forest 官网
dependency>
groupId>com.dtflys.forestgroupId>
artifactId>forest-spring-boot-starterartifactId>
version>1.5.32version>
dependency>
配置:
forest:
max-connections: 1000 # 连接池最大连接数
connect-timeout: 3000 # 连接超时时间,单位为毫秒
read-timeout: 3000 # 数据读取超时时间,单位为毫秒
扫描接口:
1.5.1以后版本可以跳过此步,不需要 @ForestScan 注解来指定扫描的包范围
只要在 Springboot
的配置类或者启动类上加上 @ForestScan
注解,并在 basePackages
属性里填上远程接口的所在的包名
public interface TestClient {
@Get("http://localhost:20001/test/queryById")
String queryById(@Header MapString, Object> headerMap, @Query MapString, Object> params);
@Post("http://localhost:20001/test/add")
String add(@Header MapString, Object> headerMap, @JSONBody UserVo userVo);
}
测试:
@RestController
@RequestMapping("/forest")
public class ForestController {
@Autowired
private TestClient testClient;
@GetMapping("/queryById")
public String queryById(Long id) {
MapString, Object> headerMap = new HashMap>();
MapString, Object> params = new HashMap>();
params.put("id", id);
headerMap.put("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODg4MDg3NzQsInVzZXJuYW1lIjoiYWRtaW4ifQ.xo5h1KwdCvMkRpUf4SkioYSpyP7j3thA86vrdz7AcGY");
return testClient.queryById(headerMap, params);
}
@PostMapping("/add")
public String add(@RequestBody UserVo userVo) {
MapString, Object> headerMap = new HashMap>();
headerMap.put("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODg4MDg3NzQsInVzZXJuYW1lIjoiYWRtaW4ifQ.xo5h1KwdCvMkRpUf4SkioYSpyP7j3thA86vrdz7AcGY");
return testClient.add(headerMap, userVo);
}
}