top.jfunc.http.component.okhttp3.OkHttp3HttpRequestExecutor Maven / Gradle / Ivy
package top.jfunc.http.component.okhttp3;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import top.jfunc.http.base.ContentCallback;
import top.jfunc.http.component.*;
import top.jfunc.http.request.HttpRequest;
import top.jfunc.http.response.ClientHttpResponse;
import java.io.IOException;
/**
* OkHttp3实现的处理
* @author xiongshiyan
* @since 2020.12.01
* @since 1.2.12
*/
public class OkHttp3HttpRequestExecutor extends BaseHttpRequestExecutor implements HttpRequestExecutor {
private RequesterFactory okHttpClientFactory;
private RequesterFactory requestBuilderFactory;
public OkHttp3HttpRequestExecutor() {
super(new DefaultOkHttp3HeaderHandler(), new DefaultOkHttp3StreamExtractor(), new DefaultOkHttp3HeaderExtractor());
this.okHttpClientFactory = new SingleOkHttp3ClientFactory();
this.requestBuilderFactory = new DefaultOkHttp3RequestBuilderFactory();
}
public OkHttp3HttpRequestExecutor(HeaderHandler requestBuilderHeaderHandler,
StreamExtractor responseStreamExtractor,
HeaderExtractor responseHeaderExtractor,
RequesterFactory okHttpClientFactory,
RequesterFactory requestBuilderFactory) {
super(requestBuilderHeaderHandler, responseStreamExtractor, responseHeaderExtractor);
this.okHttpClientFactory = okHttpClientFactory;
this.requestBuilderFactory = requestBuilderFactory;
}
@Override
public ClientHttpResponse execute(HttpRequest httpRequest, ContentCallback contentCallback) throws IOException{
//1.创建并配置OkHttpClient
OkHttpClient client = getOkHttpClientFactory().create(httpRequest);
//2.创建builder
Request.Builder builder = getRequestBuilderFactory().create(httpRequest);
//3.处理请求体
handleBody(builder , contentCallback , httpRequest);
//4.设置headers
handleHeaders(builder , httpRequest);
//5.执行请求
Response response = getResponse(client, builder, httpRequest);
return new OkHttp3ClientHttpResponse(response, httpRequest, getResponseStreamExtractor(), getResponseHeaderExtractor());
}
protected Response getResponse(OkHttpClient client, Request.Builder builder, HttpRequest httpRequest) throws IOException {
return client.newCall(builder.build()).execute();
}
public RequesterFactory getOkHttpClientFactory() {
return okHttpClientFactory;
}
public RequesterFactory getRequestBuilderFactory() {
return requestBuilderFactory;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy