背景:
最近工作上使用到了调用第三方的功能,接口是http请求的,有get和post,所以写个发起http请求的工具类。
代码:
我使用的是okhttp3
引入依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
</dependency>
创建okhttp 线程池工具类OkHttpUtils
import java.util.concurrent.TimeUnit;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
public class OkHttpUtils {
//读超时时间
private final static int READ_TIMEOUT = 10;
//连接超时时间
private final static int CONNECT_TIMEOUT = 10;
//写超时时间
private final static int WRITE_TIMEOUT = 10;
private static volatile OkHttpClient okHttpClient;
//最大线程数
private final static int MAX_IDLE_CONNECTIONS = 30 ;
//活跃线程数
private final static int KEEP_ALIVE_DURATION =10 ;
private OkHttpUtils(){
okhttp3.OkHttpClient.Builder clientBuilder = new okhttp3.OkHttpClient.Builder();
//读取超时
clientBuilder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS);
//连接超时
clientBuilder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
//写入超时
clientBuilder.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);
//自定义连接池,最大线程数,活跃线程,超时时间
clientBuilder.connectionPool(new ConnectionPool(MAX_IDLE_CONNECTIONS,KEEP_ALIVE_DURATION,TimeUnit.MINUTES));
okHttpClient = clientBuilder.build();
}
public static OkHttpClient getInstance(){
//双重if单例
if (null == okHttpClient){
synchronized (OkHttpUtils.class){
if (okHttpClient == null){
new OkHttpUtils();
return okHttpClient;
}
}
}
return okHttpClient;
}
}
创建get,post调用工具类HttpRequestHuaUtils
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.client.ClientProtocolException;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
/**
* http调用工具类
* @author hua
*/
@Slf4j
@Component("httpRequestHuaUtils")
public class HttpRequestHuaUtils {
/**
* 常规的post请求
* @param headers
* @param url
* @param jsonObject
* @return
* @throws IOException
*/
public static String httpPost(Map<String,String> headers, String url, String jsonObject) throws IOException {
log.info("请求URL->>{}",url);
log.info("请求头信息:{}", JSON.toJSON(headers));
log.info("请求参数:{}",jsonObject);
StringBuffer requestUrl = new StringBuffer(url);
OkHttpClient client = OkHttpUtils.getInstance();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, jsonObject);
Request.Builder builder = new Request.Builder();
if(Objects.nonNull(headers) && !headers.isEmpty()){
for (Map.Entry<String, String> item: headers.entrySet()) {
builder.addHeader(item.getKey(),item.getValue());
}
}
Request request = builder
.url(requestUrl.toString())
.post(RequestBody.create(jsonObject, mediaType))
.build();
Response response = client.newCall(request).execute();
if(response.isSuccessful()){
final String result = response.body().string();
log.info("请求返回结果:{}",result);
return result;
}else{
log.error("请求失败,原因:{}",response.toString());
throw new ClientProtocolException("请求失败,原因: " + response.message());
}
}
/**
* 常规的get请求
* @param headers
* @param url
* @return
* @throws IOException
*/
public static String httpGet(Map<String,String> headers, String url , Map<String,String> params ) throws IOException {
OkHttpClient client = OkHttpUtils.getInstance();
Request.Builder builder = new Request.Builder();
if(!Objects.isNull(headers) && !headers.isEmpty()){
for (Map.Entry<String, String> item: headers.entrySet()) {
builder.addHeader(item.getKey(),item.getValue());
}
}
//组装参数
if(!Objects.isNull(params) && !params.isEmpty()){
StringBuffer uri = new StringBuffer();
for (Map.Entry<String, String> item: params.entrySet()) {
uri.append("&"+item.getKey()+"="+item.getValue());
}
url = url + "?" + uri.toString().substring(1);
}
log.info("请求URL->>{}",url);
log.info("请求头信息:{}", JSON.toJSON(headers));
Request request = builder
.url(url.toString())
.build();
Response response = client.newCall(request).execute();
if(response.isSuccessful()){
final String result = response.body().string();
log.info("请求返回结果:{}",result);
return result;
}else{
log.error("请求失败,原因:{}",response.toString());
throw new ClientProtocolException("请求失败,原因: " + response.message());
}
}
}
测试:
main方法测试代码,访问百度
public static void main(String[] args) throws IOException {
HttpRequestHuaUtils client= new HttpRequestHuaUtils();
String res = client.httpGet(null, "https://www.baidu.com/" , null);
System.out.println(res);
}
调用结果:
成功,http调用工具类完成