public class HttpUtil {
private static Logger log = LoggerFactory.getLogger(HttpUtil.class);
public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.get("text/PermanentAuthorizationCodeResult-markdown; charset=utf-8");
public static final MediaType MEDIA_TYPE_URLENCODED = MediaType.get("application/PermanentAuthorizationCodeResult-www-form-urlencoded; charset=utf-8");
public static final MediaType MEDIA_TYPE_JSON = MediaType.get("application/json; charset=utf-8");
public static OkHttpClient client;
private static HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> log.info("okhttp: {}", message));
/**
* @return
*/
public static OkHttpClient client() {
if (client == null) {
// 包含header、body数据
logging.level(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
// header body 日志
builder.addInterceptor(logging);
// 设置连接超时时间
builder.connectTimeout(30, TimeUnit.SECONDS);
// 设置读取超时时间
builder.readTimeout(20, TimeUnit.SECONDS);
client = builder.build();
}
return client;
}
/**
* @return
*/
public static OkHttpClient client(Long connectTimeout, Long readTimeout) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
// 设置连接超时时间
builder.connectTimeout(connectTimeout, TimeUnit.SECONDS);
// 设置读取超时时间
builder.readTimeout(readTimeout, TimeUnit.SECONDS);
client = builder.build();
return client;
}
/**
* 发送POST请求
*
* @param url
* @param json
* @return
*/
public static <T> T httpPostWithJSON(String url, String json, Class<T> clazz) {
String body = post(url, json, MEDIA_TYPE_JSON, null);
if (StringUtils.isNotBlank(body)) {
return JsonUtil.parseObject(body, clazz);
}
return null;
}
/**
* 发送POST请求
*
* @param url
* @param json
* @return
*/
public static String postJson(String url, String json) {
return post(url, json, MEDIA_TYPE_JSON, null);
}
/**
* 发送POST请求
*
* @param url
* @param json
* @return
*/
public static String post(String url, String json, MediaType mediaType, Headers headers) {
return post(url, RequestBody.create(json, mediaType), headers);
}
/**
* 发送 get 请求
*
* @param url
* @return
*/
public static String get(String url) {
return get(url, null);
}
/**
* 发送 get 请求
*
* @param url
* @return
*/
public static String get(String url, Headers headers) {
return get(url, headers, Maps.newHashMap());
}
/**
* 发送 get 请求
*
* @param url
* @return
*/
public static String get(String url, Headers headers, Map<String, Object> parameters) {
HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
log.debug("get parameters={}", parameters);
if (parameters != null && parameters.size() > 0) {
for (Map.Entry<String, Object> param : parameters.entrySet()) {
httpBuilder.addQueryParameter(param.getKey(), StringUtil.toString(param.getValue(), ""));
}
}
Request.Builder builder = new Request.Builder();
builder.url(httpBuilder.build());
log.debug("get url={}", url);
if (headers != null && headers.size() > 0) {
builder.headers(headers);
log.debug("get headers={}", headers);
}
builder.get();
try {
Response response = client().newCall(builder.build()).execute();
log.info("url={},protocol:{},code:{},message:{}", url, response.protocol(), response.code(), response.message());
String string = response.body().string();
log.debug("response: {}", string);
if (response.isSuccessful()) {
return string;
}
return null;
} catch (Exception e) {
log.debug("url={},onFailure: {}", url, e.getMessage());
//log.debug("getStackTrace: {}", e.getStackTrace());
}
return null;
}
/**
* 设置请求头
*
* @param headersParams
* @return
*/
public static Headers setHeaders(Map<String, String> headersParams) {
Headers.Builder builder = new Headers.Builder();
if (headersParams != null) {
Iterator<String> iterator = headersParams.keySet().iterator();
String key = "";
while (iterator.hasNext()) {
key = iterator.next().toString();
builder.add(key, headersParams.get(key));
log.info("headers key={},value={}", key, headersParams.get(key));
}
}
return builder.build();
}
/**
* 发送POST请求
*
* @param url
* @param params
* @return
*/
public static String post(String url, Map<String, String> params, Headers headers) {
FormBody.Builder formBuilder = new FormBody.Builder();
Set<String> keySet = params.keySet();
for (String key : keySet) {
formBuilder.add(key, params.get(key));
}
return post(url, formBuilder.build(), headers);
}
/**
* 发送POST请求
*
* @param url
* @param bean
* @return
*/
public static <T> String post(String url, T bean, Headers headers) {
FormBody.Builder formBuilder = new FormBody.Builder();
if (bean != null) {
BeanMap beanMap = BeanMap.create(bean);
for (Object key : beanMap.keySet()) {
formBuilder.add(StringUtil.toString(key), StringUtil.toString(beanMap.get(key)));
}
}
return post(url, formBuilder.build(), headers);
}
/**
* 发送POST请求
*
* @param url
* @param requestBody
* @return
*/
public static String post(String url, RequestBody requestBody, Headers headers) {
Request.Builder builder = new Request.Builder();
builder.url(url);
log.debug("post url={}", url);
if (headers != null && headers.size() > 0) {
builder.headers(headers);
log.debug("post headers={}", headers);
}
log.debug("post requestBody ={}", requestBody);
builder.post(requestBody);
try {
Response response = client().newCall(builder.build()).execute();
log.info("url={},protocol:{},code:{},message:{}", url, response.protocol(), response.code(), response.message());
String string = response.body().string();
log.debug("response: {}", string);
if (response.isSuccessful()) {
return string;
}
return null;
} catch (Exception e) {
log.debug("url={},onFailure: {}", url, e.getMessage());
//log.debug("getStackTrace: {}", e.getStackTrace());
}
return null;
}
/**
* 异步 发送POST请求 异步
*
* @param url
* @param requestBody
* @return
*/
public static void postAsyn(String url, RequestBody requestBody, Headers headers, Callback callback) {
Request.Builder builder = new Request.Builder();
builder.url(url);
log.debug("postAsyn url={}", url);
if (headers != null && headers.size() > 0) {
builder.headers(headers);
log.debug("post headers={}", headers);
}
builder.post(requestBody);
Request request = builder.build();
client().newCall(request).enqueue(callback);
}
/**
* 异步 发送get请求 异步
*
* @param url
* @return
*/
public static void getAsyn(String url, Headers headers, Callback callback) {
Request.Builder builder = new Request.Builder();
builder.url(url);
log.debug("getAsyn url={}", url);
if (headers != null && headers.size() > 0) {
builder.headers(headers);
log.debug("get headers={}", headers);
}
builder.get();
Request request = builder.build();
client().newCall(request).enqueue(callback);
}
/**
* 发送get请求 异步
*
* @param url
* @return
*/
public static void getAsyn(String url, Callback callback) {
getAsyn(url, null, callback);
}
/**
* 发送POST请求
*
* @return
*/
public static Callback callbackDemo() {
return new Callback() {
@Override
public void onFailure(Call call, IOException e) {
log.info("error message = {}", e.getMessage());
log.error("e={}", e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
log.debug("response= {}", response);
log.info("response = {}", response.body().string());
}
};
}
}