com.eworkcloud.okhttp.OkHttpTemplate Maven / Gradle / Ivy
package com.eworkcloud.okhttp;
import com.eworkcloud.okhttp.enums.ContentType;
import com.eworkcloud.okhttp.enums.HttpMethod;
import com.eworkcloud.okhttp.model.OkHttpMessage;
import okhttp3.*;
import org.springframework.util.ObjectUtils;
import java.io.IOException;
import java.util.stream.Collectors;
public class OkHttpTemplate {
private OkHttpClient okHttpClient;
public OkHttpTemplate(OkHttpClient okHttpClient) {
this.okHttpClient = okHttpClient;
}
private RequestBody buildRequestBody(OkHttpMessage message) {
if (message.getContentType() == ContentType.JSON) {
MediaType mediaType = MediaType.parse(ContentType.JSON.value());
return RequestBody.create(mediaType, message.getBodyString());
} else {
MediaType mediaType = MediaType.parse(ContentType.FORM.value());
return RequestBody.create(mediaType, message.getBodyString());
}
}
private void attachQuery(Request.Builder builder, OkHttpMessage message) {
String url = message.getUrl();
if (!ObjectUtils.isEmpty(message.getQueryMap())) {
String queryString = message.getQueryMap().entrySet().stream()
.map(entry -> String.format("%s=%s", entry.getKey(), entry.getValue()))
.collect(Collectors.joining("&"));
url = String.format("%s%s%s", url, url.contains("?") ? "&" : "?", queryString);
}
builder.url(url);
}
private void attachHeader(Request.Builder builder, OkHttpMessage message) {
if (null != message.getHeaderMap() && !message.getHeaderMap().isEmpty()) {
message.getHeaderMap().forEach(builder::addHeader);
}
}
private Request buildRequest(OkHttpMessage message) {
Request.Builder builder = new Request.Builder();
attachQuery(builder, message);
attachHeader(builder, message);
if (message.getMethod() == HttpMethod.GET) {
builder.get();
} else if (message.getMethod() == HttpMethod.POST) {
builder.post(buildRequestBody(message));
} else if (message.getMethod() == HttpMethod.PUT) {
builder.post(buildRequestBody(message));
} else if (message.getMethod() == HttpMethod.DELETE) {
builder.delete();
} else if (message.getMethod() == HttpMethod.HEAD) {
builder.head();
}
return builder.build();
}
/**
* 同步执行方法(GET, POST, PUT, DELETE, HEAD) - HTTP/HTTPS
*
* @param message 请求对象
* @return 响应实体
*/
public Response execute(OkHttpMessage message) {
try {
return okHttpClient.newCall(buildRequest(message)).execute();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
/**
* 异步执行方法(GET, POST, PUT, DELETE, HEAD) - HTTP/HTTPS
*
* @param message 请求对象
* @param callback 异步回调
*/
public void enqueue(OkHttpMessage message, Callback callback) {
okHttpClient.newCall(buildRequest(message)).enqueue(callback);
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy