Example usage for org.apache.http.client.config RequestConfig custom

List of usage examples for org.apache.http.client.config RequestConfig custom

Introduction

In this page you can find the example usage for org.apache.http.client.config RequestConfig custom.

Prototype

public static RequestConfig.Builder custom() 

Source Link

Usage

From source file:com.pinterest.jbender.executors.http.FiberApacheHttpClientRequestExecutor.java

public FiberApacheHttpClientRequestExecutor(final Validator<CloseableHttpResponse> resValidator,
        final int maxConnections, final int timeout, final int parallelism) throws IOReactorException {
    final DefaultConnectingIOReactor ioreactor = new DefaultConnectingIOReactor(IOReactorConfig.custom()
            .setConnectTimeout(timeout).setIoThreadCount(parallelism).setSoTimeout(timeout).build());

    final PoolingNHttpClientConnectionManager mngr = new PoolingNHttpClientConnectionManager(ioreactor);
    mngr.setDefaultMaxPerRoute(maxConnections);
    mngr.setMaxTotal(maxConnections);/*from w  ww  .j  a v  a  2s. co m*/

    final CloseableHttpAsyncClient ahc = HttpAsyncClientBuilder.create().setConnectionManager(mngr)
            .setDefaultRequestConfig(RequestConfig.custom().setLocalAddress(null).build()).build();

    client = new FiberHttpClient(ahc);
    validator = resValidator;
}

From source file:com.jaspersoft.studio.data.adapter.JSSBuiltinDataFileServiceFactory.java

@Override
public DataFileService createService(JasperReportsContext context, DataFile dataFile) {
    if (dataFile instanceof RepositoryDataLocation) {
        return new RepositoryDataLocationService(context, (RepositoryDataLocation) dataFile);
    }/*from   w  ww  .ja  v  a 2s.  co  m*/
    if (dataFile instanceof HttpDataLocation) {
        return new HttpDataService(context, (HttpDataLocation) dataFile) {
            @Override
            protected CloseableHttpClient createHttpClient(Map<String, Object> parameters) {
                HttpClientBuilder clientBuilder = HttpClients.custom();
                HttpUtils.setupProxy(clientBuilder);
                // single connection
                BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager();
                clientBuilder.setConnectionManager(connManager);

                // ignore cookies for now
                RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES)
                        .build();
                clientBuilder.setDefaultRequestConfig(requestConfig);

                HttpClientContext clientContext = HttpClientContext.create();

                setAuthentication(parameters, clientContext);

                CloseableHttpClient client = clientBuilder.build();
                return client;
            }
        };
    }
    return null;
}

From source file:com.mywork.framework.util.RemoteHttpUtil.java

/**
 * ?? Post/*ww  w.j a v  a2s  . c o m*/
 * @return
 */
public static String doPost(String contentUrl, Map<String, String> headerMap, String jsonBody) {
    String result = null;
    CloseableHttpResponse response = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost post = new HttpPost(contentUrl);
    RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT_SECONDS * 1000)
            .setConnectTimeout(TIMEOUT_SECONDS * 1000).setSocketTimeout(TIMEOUT_SECONDS * 1000).build();
    post.setConfig(config);

    try {
        if (headerMap != null && !headerMap.isEmpty()) {
            for (Map.Entry<String, String> m : headerMap.entrySet()) {
                post.setHeader(m.getKey(), m.getValue());
            }
        }

        if (jsonBody != null) {
            StringEntity entity = new StringEntity(jsonBody, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            post.setEntity(entity);
        }
        long start = System.currentTimeMillis();
        response = httpClient.execute(post);
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
        logger.info("url = " + contentUrl + " request spend time = " + (System.currentTimeMillis() - start));
        EntityUtils.consume(entity);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return result;
}

From source file:com.sumologic.log4j.http.SumoHttpSender.java

public void init() {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectionTimeout).build();

    HttpClientBuilder builder = HttpClients.custom()
            .setConnectionManager(new PoolingHttpClientConnectionManager())
            .setDefaultRequestConfig(requestConfig);

    HttpProxySettingsCreator creator = new HttpProxySettingsCreator(proxySettings);
    creator.configureProxySettings(builder);

    httpClient = builder.build();/*from  ww w  .  j  av  a2s .  co m*/
}

From source file:org.apache.trafficcontrol.client.RestApiSession.java

public void open() {
    if (httpclient == null) {
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD) //User standard instead of default. Default will result in cookie parse exceptions with the Mojolicous cookie
                .setConnectTimeout(5000).build();
        CookieStore cookieStore = new BasicCookieStore();
        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookieStore);

        httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(globalConfig)
                .setDefaultCookieStore(cookieStore).build();
    }/*  w ww .  j a  v a2s .c o  m*/

    if (!httpclient.isRunning()) {
        httpclient.start();
    }
}

From source file:MainFrame.HttpCommunicator.java

public void setCombos(JComboBox comboGroups, JComboBox comboDates, LessonTableModel tableModel)
        throws MalformedURLException, IOException {
    BufferedReader in = null;// ww  w . j av  a  2s.  com
    if (SingleDataHolder.getInstance().isProxyActivated) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword));

        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                .build();

        HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress,
                SingleDataHolder.getInstance().proxyPort);

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");
        post.setConfig(config);

        StringBody head = new StringBody(new JSONObject().toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apideskviewer.getAllLessons", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);

        InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8));

        in = new BufferedReader(new InputStreamReader(stream));
    } else {
        URL obj = new URL(SingleDataHolder.getInstance().hostAdress);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "apideskviewer.getAllLessons={}";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + SingleDataHolder.getInstance().hostAdress);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    }

    JSONParser parser = new JSONParser();
    try {
        Object parsedResponse = parser.parse(in);

        JSONObject jsonParsedResponse = (JSONObject) parsedResponse;

        for (int i = 0; i < jsonParsedResponse.size(); i++) {
            String s = (String) jsonParsedResponse.get(String.valueOf(i));
            String[] splittedPath = s.split("/");
            DateFormat DF = new SimpleDateFormat("yyyyMMdd");
            Date d = DF.parse(splittedPath[1].replaceAll(".bin", ""));
            Lesson lesson = new Lesson(splittedPath[0], d, false);
            String group = splittedPath[0];
            String date = new SimpleDateFormat("dd.MM.yyyy").format(d);

            if (((DefaultComboBoxModel) comboGroups.getModel()).getIndexOf(group) == -1) {
                comboGroups.addItem(group);
            }
            if (((DefaultComboBoxModel) comboDates.getModel()).getIndexOf(date) == -1) {
                comboDates.addItem(date);
            }
            tableModel.addLesson(lesson);
        }
    } catch (Exception ex) {
    }
}

From source file:io.dropwizard.websockets.DropWizardWebsocketsTest.java

@Before
public void setUp() throws Exception {
    this.client = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(10000)
            .setConnectTimeout(10000).setConnectionRequestTimeout(10000).build()).build();
    this.om = new ObjectMapper();
    this.wsClient = ClientManager.createClient();
    wsClient.getProperties().put(ClientProperties.HANDSHAKE_TIMEOUT, 10000);
}

From source file:co.paralleluniverse.fibers.servlet.FiberHttpServletTest.java

@Before
public void setUp() throws Exception {
    this.server = cls.newInstance();
    // snippet servlet registration
    server.addServlet("test", FiberTestServlet.class, "/");
    // end of snippet
    server.addServlet("forward", FiberForwardServlet.class, "/forward");
    server.addServlet("inline", FiberForwardServlet.class, "/inline");
    server.addServlet("redirect", FiberRedirectServlet.class, "/redirect");
    server.start();/* ww  w  .  j  a  v  a  2 s  .  c o m*/
    this.client = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(5000)
            .setConnectTimeout(5000).setConnectionRequestTimeout(5000).build()).build();
}

From source file:com.spotify.helios.serviceregistration.skydns.MiniEtcdClient.java

MiniEtcdClient(final String baseUri, final int connectTimeout, final int connectionRequestTimeout,
        final int socketTimeout) {
    httpClient = HttpAsyncClients.custom()
            .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(connectTimeout)
                    .setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout)
                    .build())/*from   www  .j  a va2  s .  co  m*/
            .build();
    httpClient.start();
    this.baseUri = baseUri;
}

From source file:com.cloud.agent.direct.download.HttpsDirectTemplateDownloader.java

public HttpsDirectTemplateDownloader(String url, Long templateId, String destPoolPath, String checksum,
        Map<String, String> headers) {
    super(url, templateId, destPoolPath, checksum, headers);
    SSLContext sslcontext = null;
    try {//from w w  w. j  av  a  2 s .c o  m
        sslcontext = getSSLContext();
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException
            | KeyManagementException e) {
        throw new CloudRuntimeException("Failure getting SSL context for HTTPS downloader: " + e.getMessage());
    }
    SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000)
            .setSocketTimeout(5000).build();
    httpsClient = HttpClients.custom().setSSLSocketFactory(factory).setDefaultRequestConfig(config).build();
    createUriRequest(url, headers);
}