com.gitee.apanlh.util.net.http.handler.HttpContentLengthConfigureChain Maven / Gradle / Ivy
package com.gitee.apanlh.util.net.http.handler;
import com.gitee.apanlh.exp.HttpConfigException;
import com.gitee.apanlh.exp.HttpException;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.net.http.BaseHttpConfigure;
import com.gitee.apanlh.util.net.http.HttpBody;
import com.gitee.apanlh.util.net.http.HttpClient;
import com.gitee.apanlh.util.net.http.HttpRequest;
import com.gitee.apanlh.util.net.http.handler.body.cast.HttpRequestBodyCast;
import com.gitee.apanlh.util.reflection.ClassConvertUtils;
import com.gitee.apanlh.util.reflection.ClassTypeUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.http.HttpMethod;
import java.net.HttpURLConnection;
/**
* HTTP配置拦截器,装配实现对HTTP请求长度处理
*
* @author Pan
*/
public class HttpContentLengthConfigureChain implements HttpRequestInterceptor, BaseHttpConfigure {
/** 请求内容类型 */
private static final String CONTENT_LENGTH = "Content-Length";
@Override
public HttpRequest chain(HttpRequest httpRequest, HttpClient httpClient, HttpRequestBodyCast bodyCast, HttpInterceptorChain chain) throws HttpException {
return chain.proceed(configure(httpRequest, httpClient), httpClient);
}
@Override
public HttpRequest configure(HttpRequest httpRequest, HttpClient httpClient) throws HttpConfigException {
HttpURLConnection client = httpClient.getClient();
HttpBody httpBody = httpRequest.getBody();
// 直接构建GET请求默认不添加
if (httpBody == null && Eq.enums(HttpMethod.GET, httpRequest.getMethod())) {
return httpRequest;
}
// Content-Length
Object requestBody = httpBody.getRequestBody();
if (ValidParam.isNotNull(requestBody)) {
Class> clazz = requestBody.getClass();
int len = 0;
if (ClassTypeUtils.isString(clazz)) {
len = ClassConvertUtils.castString(requestBody).getBytes().length;
}
if (ClassTypeUtils.isArrayByte(clazz)) {
len = ClassConvertUtils.castArrayByte(requestBody).length;
}
if (len > 0) {
client.setRequestProperty(CONTENT_LENGTH, ClassConvertUtils.toStr(len));
}
}
return httpRequest;
}
}