net.lulihu.http.builder.HttpPostPayloadBuilder Maven / Gradle / Ivy
package net.lulihu.http.builder;
import com.alibaba.fastjson.JSON;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Http Post 载荷请求构建
*/
public class HttpPostPayloadBuilder extends HttpBuilder {
HttpPostPayloadBuilder(String url) {
super(url);
}
/**
* 请求参数
*/
private String params;
/**
* 设置post载荷请求参数
*
* @param postPayloadParam 参数
* @return {@linkplain HttpPostPayloadBuilder}
*/
public HttpPostPayloadBuilder setParam(String postPayloadParam) {
this.params = postPayloadParam;
return this;
}
/**
* 设置post载荷请求参数
*
* @param postPayloadJson 参数
* @return {@linkplain HttpPostPayloadBuilder}
*/
public HttpPostPayloadBuilder setParam(Object postPayloadJson) {
this.params = JSON.toJSONString(postPayloadJson);
return this;
}
/**
* 设置请求头信息
*
* @param header 头部信息
* @return {@linkplain HttpPostPayloadBuilder}
*/
public HttpPostPayloadBuilder setHeader(Map header) {
super.setHeader(header);
return this;
}
/**
* 添加请求头信息
*
* @param key 键
* @param value 值
* @return {@linkplain HttpPostPayloadBuilder}
*/
public HttpPostPayloadBuilder addHeader(String key, String value) {
super.addHeader(key, value);
return this;
}
/**
* 设置连接超时时间
*
* @param timeout 超时时间
* @param unit 时间单位
* @return {@linkplain HttpPostPayloadBuilder}
*/
public HttpPostPayloadBuilder setConnectTimeout(long timeout, TimeUnit unit) {
super.setConnectTimeout(timeout, unit);
return this;
}
/**
* 设置读取超时时间
*
* @param timeout 超时时间
* @param unit 时间单位
* @return {@linkplain HttpPostPayloadBuilder}
*/
public HttpPostPayloadBuilder setReadTimeout(long timeout, TimeUnit unit) {
super.setReadTimeout(timeout, unit);
return this;
}
/**
* 添加请求拦截器
*
* @param requestInterceptor 请求拦截器
* @return {@linkplain HttpPostPayloadBuilder}
*/
@Override
public HttpPostPayloadBuilder addRequestInterceptor(RequestInterceptor requestInterceptor) {
super.addRequestInterceptor(requestInterceptor);
return this;
}
/**
* 添加响应拦截器
*
* @param responseInterceptor 响应拦截器
* @return {@linkplain HttpPostPayloadBuilder}
*/
@Override
public HttpPostPayloadBuilder addResponseInterceptor(ResponseInterceptor responseInterceptor) {
super.addResponseInterceptor(responseInterceptor);
return this;
}
/**
* 添加网络层拦截器
*
* @param interceptor 网络层拦截器
* @return {@linkplain HttpPostPayloadBuilder}
*/
@Override
public HttpPostPayloadBuilder addNetInterceptor(Interceptor interceptor) {
super.addNetInterceptor(interceptor);
return this;
}
/**
* 发送Post载荷请求
*
* @return {@linkplain HttpPostPayloadBuilder}
* @throws HttpRequestException 请求出现例外
*/
public HttpPostPayloadBuilder send() throws HttpRequestException {
// 请求地址
requestBuilder.url(url);
// 构建请求主体参数
if (params == null) {
throw new IllegalArgumentException("请求参数不可为空");
}
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), params);
requestBuilder.post(body);
// 发送请求
super.sendRequest();
return this;
}
}