引入依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.10.0</version>
</dependency>
配置文件
## OkHttpConfig
ok:
http:
connect-timeout: 60000
read-timeout: 300000
write-timeout: 300000
max-idle-connections: 5
keep-alive-duration: 5
工具类封装
package com.tiger.util;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
@Component
@Slf4j
public class OkHttpUtils {
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final MediaType XML = MediaType.parse("application/xml; charset=utf-8");
@Autowired
private OkHttpClient okHttpClient;
public String doGet(String url) {
return doGet(url, null, null);
}
public String doGet(String url, Map<String, String> params) {
return doGet(url, params, null);
}
public String doGet(String url, String[] headers) {
return doGet(url, null, headers);
}
public String doGet(String url, Map<String, String> params, String[] headers) {
StringBuilder sb = new StringBuilder(url);
if (params != null && params.keySet().size() > 0) {
boolean firstFlag = true;
for (String key : params.keySet()) {
if (firstFlag) {
sb.append("?").append(key).append("=").append(params.get(key));
firstFlag = false;
} else {
sb.append("&").append(key).append("=").append(params.get(key));
}
}
}
Request.Builder builder = new Request.Builder();
if (headers != null && headers.length > 0) {
if (headers.length % 2 == 0) {
for (int i = 0; i < headers.length; i = i + 2) {
builder.addHeader(headers[i], headers[i + 1]);
}
} else {
log.warn("headers's length[{}] is error.", headers.length);
}
}
Request request = builder.url(sb.toString()).build();
log.info("do get request and url[{}]", sb.toString());
return execute(request);
}
public String doPost(String url, Map<String, String> params) {
FormBody.Builder builder = new FormBody.Builder();
if (params != null && params.keySet().size() > 0) {
for (String key : params.keySet()) {
builder.add(key, params.get(key));
}
}
Request request = new Request.Builder().url(url).post(builder.build()).build();
log.info("do post request and url[{}]", url);
return execute(request);
}
public String doPostJson(String url, String json) {
log.info("do post request and url[{}]", url);
return exectePost(url, json, JSON);
}
public String doPostXml(String url, String xml) {
log.info("do post request and url[{}]", url);
return exectePost(url, xml, XML);
}
private String exectePost(String url, String data, MediaType contentType) {
RequestBody requestBody = RequestBody.create(contentType, data);
Request request = new Request.Builder().url(url).post(requestBody).build();
return execute(request);
}
private String execute(Request request) {
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
log.error(ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return "";
}
public static boolean isJsonValid(String inputJosn) {
boolean ret = true;
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
JsonFactory factory = mapper.getFactory();
JsonNode jsonObj = null;
try {
JsonParser parser = factory.createParser(inputJosn);
jsonObj = mapper.readTree(parser);
} catch (IOException e) {
ret = false;
}
return ret;
}
public static void main(String[] args) throws IOException {
boolean ret = isJsonValid("{\n" +
" \"bizTable\": \"T_KKGL_JXB\",\n" +
" \"bizInstanceId\": \"1582185854538588160\",\n" +
" \"content\": \"测试消息\",\n" +
" \"title\": \"test标题\"" +
" \n" +
"}");
System.out.println(ret);
}
}
使用示例
String url = "https://www.baidu.com?clientId=tiger&signature=7758258";
Map<String, Object> map = new HashMap<>();
map.put("title", dto.getTitle());
map.put("content", dto.getContent());
map.put("receivers", dto.getReceivers());
String retData = okHttpUtils.doPostJson(url, JsonUtil.obj2json(map));