需要的包
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
private static final OkHttpClient OKHTTP_CLIENT = new OkHttpClient.Builder()
.connectTimeout(120, TimeUnit.SECONDS)
.readTimeout(120,TimeUnit.SECONDS)
.writeTimeout(120,TimeUnit.SECONDS)
.build();
private static final MediaType MEDIA_TYPE = MediaType.get("application/json; charset=utf-8");
/**
* OKHTTP POST 同步請求
* @param reqUrl 地址
* @param headers 頭部信息
* @param params 請求參數(shù)
* @return
*/
public static String okHttpPost(String reqUrl , Map<String,String> headers, Map<String,String> params){
RequestBody body = RequestBody.create(MEDIA_TYPE, JSONObject.toJSONString(params));
// 發(fā)送請求
Request request =getReqBuilder(reqUrl,headers).post(body).build();
try{
Response response = OKHTTP_CLIENT.newCall(request).execute();
return response.body().string();
}catch (Exception e){
throw new RuntimeException("HTTP POST同步請求失敗 URL:"+reqUrl,e);
}
}
/**
* OKHTTP GET 同步 請求
* @param url 地址
* @param params 參數(shù)
* @return
*/
public static String okHttpGet(String url, Map<String,String> headers, Map<String,String> params){
url = getParasmHandle(url,params);
// 發(fā)送請求
Request request = getReqBuilder(url, headers).build();
try{
Response response = OKHTTP_CLIENT.newCall(request).execute();
return response.body().string();
}catch (Exception e){
log.error(e.getMessage(),e);
return null;
}
}
/**
* OKHTTP GET 異步 請求
* @param url 地址
* @param params 參數(shù)
* @return
*/
public static void okHttpGetAsyn(String url, Map<String,String> headers, Map<String,String> params,Callback callback){
url = getParasmHandle(url,params);
// 發(fā)送請求
Request request = getReqBuilder(url, headers).build();
try{
OKHTTP_CLIENT.newCall(request).enqueue(callback);
}catch (Exception e){
throw new RuntimeException("HTTP GET異步請求失敗 URL:"+url,e);
}
}
/**
* OKHTTP POST 異步請求
* @param reqUrl 地址
* @param headers 頭部信息
* @param params 請求參數(shù)
* @return
*/
public static void okHttpPostAsyn(String reqUrl , Map<String,String> headers, Map<String,String> params,Callback callback){
RequestBody body = RequestBody.create(MEDIA_TYPE, JSONObject.toJSONString(params));
// 發(fā)送請求
Request request = getReqBuilder(reqUrl, headers).post(body).build();
try{
OKHTTP_CLIENT.newCall(request).enqueue(callback);
}catch (Exception e){
throw new RuntimeException("HTTP POST異步請求失敗 URL:"+reqUrl,e);
}
}
/**
* 初始化 請求
* @param url
* @param headers
* @return
*/
private static Request.Builder getReqBuilder(String url, Map<String, String> headers){
Request.Builder builder = new Request.Builder();
builder.header("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36");
if(headers!=null && !headers.isEmpty()) {
headers.forEach(builder::addHeader);
}
builder.url(url);
return builder;
}
/**
* GET 請求參數(shù)處理
* @param url
* @param params
* @return
*/
private static String getParasmHandle(String url,Map<String,String> params){
StringBuilder stringBuilder = new StringBuilder();
if(params!=null && !params.isEmpty()) {
params.keySet().forEach(res -> {
if (StringUtils.isNotBlank(stringBuilder) || url.contains("?")) {
stringBuilder.append("&");
} else {
stringBuilder.append("?");
}
try {
stringBuilder.append(String.format("%s=%s", res, URLEncoder.encode(params.get(res), "UTF-8")));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
});
}
return url + stringBuilder;
}