net.lulihu.http.builder.HttpGetBuilder Maven / Gradle / Ivy
package net.lulihu.http.builder;
import lombok.extern.slf4j.Slf4j;
import net.lulihu.ObjectKit.MapKit;
import okhttp3.Interceptor;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Http Get 请求构建
*/
@Slf4j
public class HttpGetBuilder extends HttpBuilder {
/**
* 请求参数
*/
private Map params;
HttpGetBuilder(String url) {
super(url);
}
/**
* 设置请求头信息
*
* @param header 头部信息
* @return {@linkplain HttpGetBuilder}
*/
public HttpGetBuilder setHeader(Map header) {
super.setHeader(header);
return this;
}
/**
* 添加请求头信息
*
* @param key 键
* @param value 值
* @return {@linkplain HttpGetBuilder}
*/
public HttpGetBuilder addHeader(String key, String value) {
super.addHeader(key, value);
return this;
}
/**
* 设置连接超时时间
*
* @param timeout 超时时间
* @param unit 时间单位
* @return {@linkplain HttpBuilder}
*/
public HttpGetBuilder setConnectTimeout(long timeout, TimeUnit unit) {
super.setConnectTimeout(timeout, unit);
return this;
}
/**
* 设置读取超时时间
*
* @param timeout 超时时间
* @param unit 时间单位
* @return {@linkplain HttpBuilder}
*/
public HttpGetBuilder setReadTimeout(long timeout, TimeUnit unit) {
super.setReadTimeout(timeout, unit);
return this;
}
/**
* 添加请求拦截器
*
* @param requestInterceptor 请求拦截器
* @return {@linkplain HttpGetBuilder}
*/
@Override
public HttpGetBuilder addRequestInterceptor(RequestInterceptor requestInterceptor) {
super.addRequestInterceptor(requestInterceptor);
return this;
}
/**
* 添加响应拦截器
*
* @param responseInterceptor 响应拦截器
* @return {@linkplain HttpGetBuilder}
*/
@Override
public HttpGetBuilder addResponseInterceptor(ResponseInterceptor responseInterceptor) {
super.addResponseInterceptor(responseInterceptor);
return this;
}
/**
* 添加网络层拦截器
*
* @param interceptor 网络层拦截器
* @return {@linkplain HttpGetBuilder}
*/
@Override
public HttpGetBuilder addNetInterceptor(Interceptor interceptor) {
super.addNetInterceptor(interceptor);
return this;
}
/**
* 设置get请求参数
*
* @param getParam 参数
* @return {@linkplain HttpGetBuilder}
*/
public HttpGetBuilder setParam(Map getParam) {
this.params = getParam;
return this;
}
/**
* 添加get请求参数
*
* @param key 键
* @param value 值
* @return {@linkplain HttpGetBuilder}
*/
public HttpGetBuilder addParam(String key, String value) {
if (this.params == null) {
this.params = new HashMap<>();
}
this.params.put(key, value);
return this;
}
/**
* 发送Get请求
*
* @return {@linkplain HttpGetBuilder}
* @throws HttpRequestException 请求出现例外
*/
public HttpGetBuilder send() throws HttpRequestException {
String urlAndParam = null;
if (MapKit.isNotEmpty(params)) {
StringBuilder builder = new StringBuilder();
for (String key : params.keySet()) {
builder.append(key).append("=").append(params.get(key)).append("&");
}
urlAndParam = url + "?" + builder.toString().substring(0, builder.length() - 1);
}
// 设置请求方式
requestBuilder.get()
// 设置 url + 参数
.url(urlAndParam == null ? url : urlAndParam);
// 发送请求
super.sendRequest();
return this;
}
}