Search in sources :

Example 36 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project swift by luastar.

the class HttpClientUtils method get.

public static String get(HttpParam param) {
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {
        HttpGet httpGet = new HttpGet(param.getUrl());
        // 超时设置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(param.getTimeout()).setConnectTimeout(param.getTimeout()).setConnectionRequestTimeout(param.getTimeout()).build();
        httpGet.setConfig(requestConfig);
        // head设置
        if (ObjUtils.isNotEmpty(param.getHeaderMap())) {
            for (Map.Entry<String, String> entry : param.getHeaderMap().entrySet()) {
                httpGet.setHeader(entry.getKey(), entry.getValue());
            }
        }
        // requestId
        String requestId = ObjUtils.ifEmpty(MDC.get(MDC_KEY_REQUESTID), MDC.get(MDC_KEY_REQUEST_ID));
        if (ObjUtils.isNotEmpty(requestId)) {
            httpGet.setHeader(MDC_KEY_REQUESTID, requestId);
        }
        httpclient = createHttpClient(param.getUrl());
        long start = System.currentTimeMillis();
        response = httpclient.execute(httpGet);
        long end = System.currentTimeMillis();
        int status = response.getStatusLine().getStatusCode();
        logger.info("请求url:{},结果状态:{},耗时:{}毫秒。", param.getUrl(), status, ((end - start)));
        if (status >= 200 && status < 300) {
            HttpEntity entity = response.getEntity();
            return entity != null ? EntityUtils.toString(entity, param.getCharset()) : null;
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        org.apache.http.client.utils.HttpClientUtils.closeQuietly(response);
        org.apache.http.client.utils.HttpClientUtils.closeQuietly(httpclient);
    }
    return null;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) CertificateException(java.security.cert.CertificateException)

Example 37 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project swift by luastar.

the class HttpClientUtils method postHttpResult.

public static HttpResult postHttpResult(HttpParam param) {
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    HttpResult result = new HttpResult();
    try {
        HttpPost httpPost = new HttpPost(param.getUrl());
        // 超时设置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(param.getTimeout()).setConnectTimeout(param.getTimeout()).setConnectionRequestTimeout(param.getTimeout()).build();
        httpPost.setConfig(requestConfig);
        // head设置
        if (ObjUtils.isNotEmpty(param.getHeaderMap())) {
            for (Map.Entry<String, String> entry : param.getHeaderMap().entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        // requestId
        String requestId = ObjUtils.ifEmpty(MDC.get(MDC_KEY_REQUESTID), MDC.get(MDC_KEY_REQUEST_ID));
        if (ObjUtils.isNotEmpty(requestId)) {
            httpPost.setHeader(MDC_KEY_REQUESTID, requestId);
        }
        // 参数设置
        if (ObjUtils.isNotEmpty(param.getParamMap())) {
            List<NameValuePair> nvps = new ArrayList<>();
            for (Map.Entry<String, String> entry : param.getParamMap().entrySet()) {
                // 如果没有按泛型传,需要将值转换为字符串
                nvps.add(new BasicNameValuePair(entry.getKey(), ObjUtils.toString(entry.getValue())));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, param.getCharset()));
        }
        httpclient = createHttpClient(param.getUrl());
        long start = System.currentTimeMillis();
        response = httpclient.execute(httpPost);
        long end = System.currentTimeMillis();
        int status = response.getStatusLine().getStatusCode();
        logger.info("请求url:{},结果状态:{},耗时:{}毫秒。", param.getUrl(), status, (end - start));
        result.setStatus(status);
        result.setCost(end - start);
        result.setHeaders(response.getAllHeaders());
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            byte[] content = EntityUtils.toByteArray(entity);
            if (content != null) {
                result.setInputStream(new ByteArrayInputStream(content));
            }
        }
        return result;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        result.setStatus(HttpResult.STATUS_EXP);
        result.setException(e);
    } finally {
        org.apache.http.client.utils.HttpClientUtils.closeQuietly(response);
        org.apache.http.client.utils.HttpClientUtils.closeQuietly(httpclient);
    }
    return result;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) ArrayList(java.util.ArrayList) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) CertificateException(java.security.cert.CertificateException) ByteArrayInputStream(java.io.ByteArrayInputStream) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 38 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project keycloak by keycloak.

the class OAuthRedirectUriTest method testWithCustomScheme.

@Test
public void testWithCustomScheme() throws IOException {
    oauth.clientId("custom-scheme");
    oauth.redirectUri("android-app://org.keycloak.examples.cordova/https/keycloak-cordova-example.github.io/login");
    oauth.openLoginForm();
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
    CookieStore cookieStore = new BasicCookieStore();
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(cookieStore);
    String loginUrl = driver.getCurrentUrl();
    CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();
    try {
        String loginPage = SimpleHttp.doGet(loginUrl, client).asString();
        String formAction = loginPage.split("action=\"")[1].split("\"")[0].replaceAll("&amp;", "&");
        SimpleHttp.Response response = SimpleHttp.doPost(formAction, client).param("username", "test-user@localhost").param("password", "password").asResponse();
        response.getStatus();
        assertThat(response.getFirstHeader("Location"), Matchers.startsWith("android-app://org.keycloak.examples.cordova/https/keycloak-cordova-example.github.io/login"));
    } finally {
        client.close();
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) SimpleHttp(org.keycloak.broker.provider.util.SimpleHttp) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) Test(org.junit.Test) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest)

Example 39 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project keycloak by keycloak.

the class HttpClientBuilder method build.

public CloseableHttpClient build() {
    X509HostnameVerifier verifier = null;
    if (this.verifier != null)
        verifier = new VerifierWrapper(this.verifier);
    else {
        switch(policy) {
            case ANY:
                verifier = new AllowAllHostnameVerifier();
                break;
            case WILDCARD:
                verifier = new BrowserCompatHostnameVerifier();
                break;
            case STRICT:
                verifier = new StrictHostnameVerifier();
                break;
        }
    }
    try {
        SSLConnectionSocketFactory sslsf = null;
        SSLContext theContext = sslContext;
        if (disableTrustManager) {
            theContext = SSLContext.getInstance("TLS");
            theContext.init(null, new TrustManager[] { new PassthroughTrustManager() }, new SecureRandom());
            verifier = new AllowAllHostnameVerifier();
            sslsf = new SSLConnectionSocketFactory(theContext, verifier);
        } else if (theContext != null) {
            sslsf = new SSLConnectionSocketFactory(theContext, verifier);
        } else if (clientKeyStore != null || truststore != null) {
            theContext = createSslContext("TLS", clientKeyStore, clientPrivateKeyPassword, truststore, null);
            sslsf = new SSLConnectionSocketFactory(theContext, verifier);
        } else {
            final SSLContext tlsContext = SSLContext.getInstance("TLS");
            tlsContext.init(null, null, null);
            sslsf = new SSLConnectionSocketFactory(tlsContext, verifier);
        }
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout((int) establishConnectionTimeout).setSocketTimeout((int) socketTimeout).setExpectContinueEnabled(expectContinueEnabled).build();
        org.apache.http.impl.client.HttpClientBuilder builder = HttpClients.custom().setDefaultRequestConfig(requestConfig).setSSLSocketFactory(sslsf).setMaxConnTotal(connectionPoolSize).setMaxConnPerRoute(maxPooledPerRoute).setConnectionTimeToLive(connectionTTL, connectionTTLUnit);
        if (!reuseConnections) {
            builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
        }
        if (proxyMappings != null && !proxyMappings.isEmpty()) {
            builder.setRoutePlanner(new ProxyMappingsAwareRoutePlanner(proxyMappings));
        }
        if (maxConnectionIdleTime > 0) {
            // Will start background cleaner thread
            builder.evictIdleConnections(maxConnectionIdleTime, maxConnectionIdleTimeUnit);
        }
        if (disableCookies)
            builder.disableCookieManagement();
        if (!reuseConnections) {
            builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
        }
        return builder.build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoConnectionReuseStrategy(org.apache.http.impl.NoConnectionReuseStrategy) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) StrictHostnameVerifier(org.apache.http.conn.ssl.StrictHostnameVerifier) BrowserCompatHostnameVerifier(org.apache.http.conn.ssl.BrowserCompatHostnameVerifier)

Example 40 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project SEPA by arces-wot.

the class SPARQL11Protocol method post.

/**
 * <a href="https://www.w3.org/TR/sparql11-protocol/"> SPARQL 1.1 Protocol</a>
 *
 * *
 *
 * <pre>
 *                               HTTP Method   Query String Parameters           Request Content Type                Request Message Body
 *----------------------------------------------------------------------------------------------------------------------------------------
 * update via URL-encoded POST|   POST         None                              application/x-www-form-urlencoded   URL-encoded, ampersand-separated query parameters.
 *                            |                                                                                     update (exactly 1)
 *                            |                                                                                     using-graph-uri (0 or more)
 *                            |                                                                                     using-named-graph-uri (0 or more)
 *----------------------------------------------------------------------------------------------------------------------------------------
 * update via POST directly   |    POST       using-graph-uri (0 or more)       application/sparql-update           Unencoded SPARQL update request string
 *                                            using-named-graph-uri (0 or more)
 * </pre>
 */
private Response post(UpdateRequest req) {
    StringEntity requestEntity = null;
    HttpPost post;
    String graphs = null;
    // Setting URL
    String scheme = req.getScheme();
    String host = req.getHost();
    int port = req.getPort();
    String updatePath = req.getPath();
    // Create POST request
    try {
        if (req.getHttpMethod().equals(UpdateHTTPMethod.POST)) {
            // Graphs
            for (String g : req.getDefaultGraphUri()) {
                if (graphs == null)
                    graphs = "using-graph-uri=" + g;
                else
                    graphs += "&using-graph-uri=" + g;
            }
            for (String g : req.getNamedGraphUri()) {
                if (graphs == null)
                    graphs = "using-named-graph-uri=" + g;
                else
                    graphs += "&using-named-graph-uri=" + g;
            }
            post = new HttpPost(new URI(scheme, null, host, port, updatePath, graphs, null));
            post.setHeader("Content-Type", "application/sparql-update");
            // Body
            requestEntity = new StringEntity(req.getSPARQL(), Consts.UTF_8);
        } else {
            // Graphs
            for (String g : req.getDefaultGraphUri()) {
                if (graphs == null)
                    graphs = "using-graph-uri=" + URLEncoder.encode(g, "UTF-8");
                else
                    graphs += "&using-graph-uri=" + URLEncoder.encode(g, "UTF-8");
            }
            for (String g : req.getNamedGraphUri()) {
                if (graphs == null)
                    graphs = "using-named-graph-uri=" + URLEncoder.encode(g, "UTF-8");
                else
                    graphs += "&using-named-graph-uri=" + URLEncoder.encode(g, "UTF-8");
            }
            post = new HttpPost(new URI(scheme, null, host, port, updatePath, null, null));
            post.setHeader("Content-Type", "application/x-www-form-urlencoded");
            // Body
            if (graphs != null)
                requestEntity = new StringEntity("update=" + URLEncoder.encode(req.getSPARQL(), "UTF-8") + "&" + graphs, Consts.UTF_8);
            else
                requestEntity = new StringEntity("update=" + URLEncoder.encode(req.getSPARQL(), "UTF-8"), Consts.UTF_8);
        }
    } catch (URISyntaxException e) {
        logger.error(e.getMessage());
        return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "URISyntaxException", e.getMessage());
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage());
        return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "UnsupportedEncodingException", e.getMessage());
    }
    // Accept header
    post.setHeader("Accept", req.getAcceptHeader());
    // Body
    post.setEntity(requestEntity);
    // Setting timeout
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout((int) req.getTimeout()).setConnectTimeout((int) req.getTimeout()).build();
    post.setConfig(requestConfig);
    // Add "Authorization" header if required
    String authorizationHeader = req.getAuthorizationHeader();
    if (authorizationHeader != null) {
        post.setHeader("Authorization", authorizationHeader);
    }
    return executeRequest(post, req);
}
Also used : StringEntity(org.apache.http.entity.StringEntity) HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) UnsupportedEncodingException(java.io.UnsupportedEncodingException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse)

Aggregations

RequestConfig (org.apache.http.client.config.RequestConfig)344 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)146 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)97 HttpGet (org.apache.http.client.methods.HttpGet)94 IOException (java.io.IOException)78 HttpEntity (org.apache.http.HttpEntity)67 HttpPost (org.apache.http.client.methods.HttpPost)65 HttpResponse (org.apache.http.HttpResponse)60 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)55 URI (java.net.URI)46 StringEntity (org.apache.http.entity.StringEntity)43 Map (java.util.Map)41 Test (org.junit.Test)41 BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)33 HttpHost (org.apache.http.HttpHost)32 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)32 HttpClient (org.apache.http.client.HttpClient)31 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)27 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)24 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)24