Search in sources :

Example 1 with ForestProxy

use of com.dtflys.forest.http.ForestProxy in project forest by dromara.

the class HttpclientConnectionManager method getHttpClient.

public HttpClient getHttpClient(ForestRequest request, CookieStore cookieStore) {
    HttpClientBuilder builder = HttpClients.custom();
    builder.setConnectionManager(tsConnectionManager);
    RequestConfig.Builder configBuilder = RequestConfig.custom();
    // 超时时间
    Integer timeout = request.getTimeout();
    // 连接超时时间
    Integer connectTimeout = request.connectTimeout();
    // 读取超时时间
    Integer readTimeout = request.readTimeout();
    if (TimeUtils.isNone(connectTimeout)) {
        connectTimeout = timeout;
    }
    if (TimeUtils.isNone(readTimeout)) {
        readTimeout = timeout;
    }
    // 设置请求连接超时时间
    configBuilder.setConnectTimeout(connectTimeout);
    // 设置请求数据传输超时时间
    configBuilder.setSocketTimeout(readTimeout);
    // 设置从连接池获取连接实例的超时
    // configBuilder.setConnectionRequestTimeout(-1);
    // 在提交请求之前 测试连接是否可用
    configBuilder.setStaleConnectionCheckEnabled(true);
    // 设置Cookie策略
    configBuilder.setCookieSpec(CookieSpecs.STANDARD);
    // 禁止自动重定向
    configBuilder.setRedirectsEnabled(false);
    ForestProxy forestProxy = request.getProxy();
    if (forestProxy != null) {
        HttpHost proxy = new HttpHost(forestProxy.getHost(), forestProxy.getPort());
        if (StringUtils.isNotEmpty(forestProxy.getUsername()) && StringUtils.isNotEmpty(forestProxy.getPassword())) {
            CredentialsProvider provider = new BasicCredentialsProvider();
            provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(forestProxy.getUsername(), forestProxy.getPassword()));
            builder.setDefaultCredentialsProvider(provider);
        }
        configBuilder.setProxy(proxy);
    }
    if (cookieStore != null) {
        builder.setDefaultCookieStore(cookieStore);
    }
    RequestConfig requestConfig = configBuilder.build();
    HttpClient httpClient = builder.setDefaultRequestConfig(requestConfig).disableContentCompression().build();
    return httpClient;
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) HttpClient(org.apache.http.client.HttpClient) AuthScope(org.apache.http.auth.AuthScope) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) ForestProxy(com.dtflys.forest.http.ForestProxy) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 2 with ForestProxy

use of com.dtflys.forest.http.ForestProxy in project forest by dromara.

the class OkHttp3ConnectionManager method getClient.

public OkHttpClient getClient(ForestRequest request, LifeCycleHandler lifeCycleHandler) {
    Integer timeout = request.getTimeout();
    Integer connectTimeout = request.connectTimeout();
    Integer readTimeout = request.readTimeout();
    if (TimeUtils.isNone(connectTimeout)) {
        connectTimeout = timeout;
    }
    if (TimeUtils.isNone(readTimeout)) {
        readTimeout = timeout;
    }
    OkHttpClient.Builder builder = new OkHttpClient.Builder().connectionPool(pool).dispatcher(dispatcher).connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).readTimeout(readTimeout, TimeUnit.MILLISECONDS).protocols(getProtocols(request)).followRedirects(false).followSslRedirects(false).cookieJar(new CookieJar() {

        @Override
        public void saveFromResponse(HttpUrl url, List<Cookie> okCookies) {
            ForestCookies cookies = new ForestCookies();
            for (Cookie okCookie : okCookies) {
                long currentTime = System.currentTimeMillis();
                ForestCookie cookie = ForestCookie.createFromOkHttpCookie(currentTime, okCookie);
                cookies.addCookie(cookie);
            }
            lifeCycleHandler.handleSaveCookie(request, cookies);
        }

        @Override
        public List<Cookie> loadForRequest(HttpUrl url) {
            ForestCookies cookies = new ForestCookies();
            lifeCycleHandler.handleLoadCookie(request, cookies);
            List<ForestCookie> forestCookies = cookies.allCookies();
            List<Cookie> okCookies = new ArrayList<>(forestCookies.size());
            for (ForestCookie cookie : forestCookies) {
                Duration maxAge = cookie.getMaxAge();
                Date createTime = cookie.getCreateTime();
                long expiresAt = createTime.getTime() + maxAge.toMillis();
                Cookie.Builder cookieBuilder = new Cookie.Builder();
                cookieBuilder.name(cookie.getName()).value(cookie.getValue()).expiresAt(expiresAt).path(cookie.getPath());
                if (cookie.isHostOnly()) {
                    cookieBuilder.hostOnlyDomain(cookie.getDomain());
                } else {
                    cookieBuilder.domain(cookie.getDomain());
                }
                if (cookie.isHttpOnly()) {
                    cookieBuilder.httpOnly();
                }
                if (cookie.isSecure()) {
                    cookieBuilder.secure();
                }
                Cookie okCookie = cookieBuilder.build();
                okCookies.add(okCookie);
            }
            return okCookies;
        }
    });
    // set proxy
    ForestProxy proxy = request.getProxy();
    if (proxy != null) {
        Proxy okProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy.getHost(), proxy.getPort()));
        builder.proxy(okProxy);
        if (StringUtils.isNotEmpty(proxy.getUsername())) {
            builder.proxyAuthenticator(new Authenticator() {

                @Nullable
                @Override
                public Request authenticate(@Nullable Route route, Response response) {
                    Request.Builder proxyBuilder = response.request().newBuilder();
                    String credential = Credentials.basic(proxy.getUsername(), proxy.getPassword());
                    proxyBuilder.addHeader("Proxy-Authorization", credential);
                    return proxyBuilder.build();
                }
            });
        }
    }
    if (request.isSSL()) {
        SSLSocketFactory sslSocketFactory = request.getSSLSocketFactory();
        builder.sslSocketFactory(sslSocketFactory, getX509TrustManager(request)).hostnameVerifier(request.hostnameVerifier());
    }
    // add default interceptor
    builder.addNetworkInterceptor(chain -> {
        Response response = chain.proceed(chain.request());
        return response.newBuilder().body(new OkHttpResponseBody(request, response.body(), lifeCycleHandler)).build();
    });
    return builder.build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) InetSocketAddress(java.net.InetSocketAddress) ForestCookie(com.dtflys.forest.http.ForestCookie) ForestProxy(com.dtflys.forest.http.ForestProxy) Proxy(java.net.Proxy) OkHttpResponseBody(com.dtflys.forest.backend.okhttp3.response.OkHttpResponseBody) ArrayList(java.util.ArrayList) List(java.util.List) CookieJar(okhttp3.CookieJar) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) ForestProxy(com.dtflys.forest.http.ForestProxy) Authenticator(okhttp3.Authenticator) Route(okhttp3.Route) Cookie(okhttp3.Cookie) ForestCookie(com.dtflys.forest.http.ForestCookie) ForestRequest(com.dtflys.forest.http.ForestRequest) Request(okhttp3.Request) Duration(java.time.Duration) HttpUrl(okhttp3.HttpUrl) Date(java.util.Date) Response(okhttp3.Response) ForestCookies(com.dtflys.forest.http.ForestCookies) Nullable(javax.annotation.Nullable)

Example 3 with ForestProxy

use of com.dtflys.forest.http.ForestProxy in project forest by dromara.

the class AbstractHttpclientRequestSender method getRequestLogMessage.

private <T extends HttpRequestBase> RequestLogMessage getRequestLogMessage(int retryCount, T httpReq) {
    RequestLogMessage logMessage = new RequestLogMessage();
    URI uri = httpReq.getURI();
    logMessage.setUri(uri.toASCIIString());
    logMessage.setType(httpReq.getMethod());
    logMessage.setScheme(uri.getScheme());
    logMessage.setRetryCount(retryCount);
    setLogHeaders(logMessage, httpReq);
    setLogBody(logMessage, httpReq);
    ForestProxy proxy = request.getProxy();
    if (proxy != null) {
        RequestProxyLogMessage proxyLogMessage = new RequestProxyLogMessage();
        proxyLogMessage.setHost(proxy.getHost());
        proxyLogMessage.setPort(proxy.getPort() + "");
        logMessage.setProxy(proxyLogMessage);
    }
    return logMessage;
}
Also used : RequestLogMessage(com.dtflys.forest.logging.RequestLogMessage) RequestProxyLogMessage(com.dtflys.forest.logging.RequestProxyLogMessage) URI(java.net.URI) ForestProxy(com.dtflys.forest.http.ForestProxy)

Example 4 with ForestProxy

use of com.dtflys.forest.http.ForestProxy in project forest by dromara.

the class HTTPProxyLifeCycle method beforeExecute.

@Override
public boolean beforeExecute(ForestRequest request) {
    MappingTemplate hostTemplate = (MappingTemplate) getAttribute(request, "host_temp");
    MappingTemplate portTemplate = (MappingTemplate) getAttribute(request, "port_temp");
    MappingTemplate usernameTemplate = (MappingTemplate) getAttribute(request, "username_temp");
    MappingTemplate passwordTemplate = (MappingTemplate) getAttribute(request, "password_temp");
    Object httpProxySource = request.getMethod().getExtensionParameterValue(PARAM_KEY_HTTP_PROXY_SOURCE);
    Object[] args = request.getArguments();
    String host = hostTemplate.render(args);
    String portStr = portTemplate.render(args);
    String username = null, password = null;
    if (usernameTemplate != null) {
        username = usernameTemplate.render(args);
    }
    if (passwordTemplate != null) {
        password = passwordTemplate.render(args);
    }
    int port = 80;
    if (StringUtils.isBlank(host)) {
        if (httpProxySource != null && httpProxySource instanceof HTTPProxySource) {
            request.setProxy(((HTTPProxySource) httpProxySource).getProxy(request));
            return true;
        }
        throw new ForestRuntimeException("[Forest] Proxy host cannot be empty!");
    }
    if (StringUtils.isNotBlank(portStr)) {
        try {
            port = Integer.parseInt(portStr);
        } catch (Throwable th) {
        }
    }
    ForestProxy proxy = new ForestProxy(host, port);
    if (StringUtils.isNotEmpty(username)) {
        proxy.setUsername(username);
    }
    if (StringUtils.isNotEmpty(password)) {
        proxy.setPassword(password);
    }
    request.setProxy(proxy);
    return true;
}
Also used : MappingTemplate(com.dtflys.forest.mapping.MappingTemplate) ForestRuntimeException(com.dtflys.forest.exceptions.ForestRuntimeException) HTTPProxySource(com.dtflys.forest.callback.HTTPProxySource) ForestProxy(com.dtflys.forest.http.ForestProxy)

Aggregations

ForestProxy (com.dtflys.forest.http.ForestProxy)4 OkHttpResponseBody (com.dtflys.forest.backend.okhttp3.response.OkHttpResponseBody)1 HTTPProxySource (com.dtflys.forest.callback.HTTPProxySource)1 ForestRuntimeException (com.dtflys.forest.exceptions.ForestRuntimeException)1 ForestCookie (com.dtflys.forest.http.ForestCookie)1 ForestCookies (com.dtflys.forest.http.ForestCookies)1 ForestRequest (com.dtflys.forest.http.ForestRequest)1 RequestLogMessage (com.dtflys.forest.logging.RequestLogMessage)1 RequestProxyLogMessage (com.dtflys.forest.logging.RequestProxyLogMessage)1 MappingTemplate (com.dtflys.forest.mapping.MappingTemplate)1 InetSocketAddress (java.net.InetSocketAddress)1 Proxy (java.net.Proxy)1 URI (java.net.URI)1 Duration (java.time.Duration)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 List (java.util.List)1 Nullable (javax.annotation.Nullable)1 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)1 Authenticator (okhttp3.Authenticator)1