net.lulihu.http.builder.HttpPostBuilder Maven / Gradle / Ivy
package net.lulihu.http.builder;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Http Post 请求构建
*/
public class HttpPostBuilder extends HttpBuilder {
HttpPostBuilder(String url) {
super(url);
this.builder = new FormBody.Builder();
}
/**
* 请求参数
*/
private FormBody.Builder builder;
/**
* 设置请求头信息
*
* @param header 头部信息
* @return {@linkplain HttpPostBuilder}
*/
public HttpPostBuilder setHeader(Map header) {
super.setHeader(header);
return this;
}
/**
* 添加请求头信息
*
* @param key 键
* @param value 值
* @return {@linkplain HttpPostBuilder}
*/
public HttpPostBuilder addHeader(String key, String value) {
super.addHeader(key, value);
return this;
}
/**
* 设置连接超时时间
*
* @param timeout 超时时间
* @param unit 时间单位
* @return {@linkplain HttpBuilder}
*/
public HttpPostBuilder setConnectTimeout(long timeout, TimeUnit unit) {
super.setConnectTimeout(timeout, unit);
return this;
}
/**
* 设置读取超时时间
*
* @param timeout 超时时间
* @param unit 时间单位
* @return {@linkplain HttpBuilder}
*/
public HttpPostBuilder setReadTimeout(long timeout, TimeUnit unit) {
super.setReadTimeout(timeout, unit);
return this;
}
/**
* 添加请求拦截器
*
* @param requestInterceptor 请求拦截器
* @return {@linkplain HttpPostBuilder}
*/
@Override
public HttpPostBuilder addRequestInterceptor(RequestInterceptor requestInterceptor) {
super.addRequestInterceptor(requestInterceptor);
return this;
}
/**
* 添加响应拦截器
*
* @param responseInterceptor 响应拦截器
* @return {@linkplain HttpPostBuilder}
*/
@Override
public HttpPostBuilder addResponseInterceptor(ResponseInterceptor responseInterceptor) {
super.addResponseInterceptor(responseInterceptor);
return this;
}
/**
* 添加网络层拦截器
*
* @param interceptor 网络层拦截器
* @return {@linkplain HttpPostBuilder}
*/
@Override
public HttpPostBuilder addNetInterceptor(Interceptor interceptor) {
super.addNetInterceptor(interceptor);
return this;
}
/**
* 设置post请求参数
*
* @param postParam 参数
* @return {@linkplain HttpBuilder}
*/
public HttpPostBuilder setParam(Map postParam) {
for (Map.Entry entry : postParam.entrySet()) {
this.builder.add(entry.getKey(), entry.getValue());
}
return this;
}
/**
* 添加post请求参数
*
* @param key 键
* @param value 值
* @return {@linkplain HttpBuilder}
*/
public HttpPostBuilder addParam(String key, String value) {
this.builder.add(key, value);
return this;
}
/**
* 发送Post请求
*
* @return {@linkplain HttpPostBuilder}
* @throws HttpRequestException 请求出现例外
*/
public HttpPostBuilder send() throws HttpRequestException {
// 请求地址
requestBuilder.url(url);
// 请求参数
requestBuilder.post(builder.build());
// 发送请求
super.sendRequest();
return this;
}
}