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.zhch.example.commons.http.v4_5.ClientExecuteProxy.java

public static void proxyExample() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*  w ww.ja v  a2s  .c o m*/
        HttpHost proxy = new HttpHost("24.157.37.61", 8080, "http");

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet request = new HttpGet("http://www.ip.cn");
        request.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");

        request.setConfig(config);

        System.out.println(
                "Executing request " + request.getRequestLine() + " to " + request.getURI() + " via " + proxy);

        CloseableHttpResponse response = httpclient.execute(request);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity(), "utf8"));
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:org.mobicents.servlet.restcomm.http.CustomHttpClientBuilder.java

public static HttpClient build(MainConfigurationSet config) {
    SslMode mode = config.getSslMode();/*from ww  w.  j a  va2  s.c  o m*/
    int timeoutConnection = config.getResponseTimeout();
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutConnection)
            .setConnectionRequestTimeout(timeoutConnection).setSocketTimeout(timeoutConnection)
            .setCookieSpec(CookieSpecs.STANDARD).build();
    if (mode == SslMode.strict) {
        return HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
    } else {
        return buildAllowallClient(requestConfig);
    }
}

From source file:edgeserver.HTTPClient.java

void sendPost(String url, List<NameValuePair> postParams) throws Exception {

    int CONNECTION_TIMEOUT = 30 * 1000; // timeout in millis
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_TIMEOUT)
            .setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(CONNECTION_TIMEOUT).build();

    //System.out.println(postParams);

    HttpPost post = new HttpPost(url);
    post.setConfig(requestConfig);/*from w  w w  .  ja v a  2  s . co  m*/

    // add header
    post.setHeader("Host", "localhost");
    post.setHeader("User-Agent", USER_AGENT);
    post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    post.setHeader("Accept-Language", "en-US,en;q=0.5");
    post.setHeader("Cookie", getCookies());
    post.setHeader("Connection", "keep-alive");
    post.setHeader("Referer", "http://localhost/exehdager-teste/index.php/ci_login");
    post.setHeader("Content-Type", "application/x-www-form-urlencoded");

    post.setEntity(new UrlEncodedFormEntity(postParams));

    HttpResponse response = client.execute(post);

    int responseCode = response.getStatusLine().getStatusCode();

    //System.out.println("\nSending 'POST' request to URL : " + url);
    //System.out.println("Post parameters : " + postParams);
    //System.out.println("Response Code : " + responseCode);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }

    //System.out.println(result.toString());

}

From source file:tv.icntv.common.HttpClientUtil.java

public static String getContent(String url, Charset charset) throws IOException {
    HttpGet request = new HttpGet(url);
    request.setConfig(RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
            .setSocketTimeout(SOCKET_TIMEOUT).build());
    CloseableHttpClient client = HttpClientHolder.getClient();
    CloseableHttpResponse response = null;

    response = client.execute(request);//from w  w w.j  a va 2s.  c o  m
    return EntityUtils.toString(response.getEntity(), charset);

}

From source file:org.restcomm.connect.commons.common.http.CustomHttpClientBuilder.java

public static HttpClient build(MainConfigurationSet config, int timeout) {
    SslMode mode = config.getSslMode();/*from   www  . j ava2 s.  c o  m*/
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).setCookieSpec(CookieSpecs.STANDARD)
            .build();
    if (mode == SslMode.strict) {
        return HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
    } else {
        return buildAllowallClient(requestConfig);
    }
}

From source file:de.intevation.irix.ImageClient.java

/** Obtains a Report from mapfish-print service.
 *
 * @param imageUrl The url to send the request to.
 * @param timeout the timeout for the httpconnection.
 *
 * @return byte[] with the report./*w  w  w  . j  ava 2s  . co  m*/
 *
 * @throws IOException if communication with print service failed.
 * @throws ImageException if the print job failed.
 */
public static byte[] getImage(String imageUrl, int timeout) throws IOException, ImageException {

    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).build();

    CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();

    HttpGet get = new HttpGet(imageUrl);
    CloseableHttpResponse resp = client.execute(get);

    StatusLine status = resp.getStatusLine();

    byte[] retval = null;
    try {
        HttpEntity respEnt = resp.getEntity();
        InputStream in = respEnt.getContent();
        if (in != null) {
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buf = new byte[BYTE_ARRAY_SIZE];
                int r;
                while ((r = in.read(buf)) >= 0) {
                    out.write(buf, 0, r);
                }
                retval = out.toByteArray();
            } finally {
                in.close();
                EntityUtils.consume(respEnt);
            }
        }
    } finally {
        resp.close();
    }

    if (status.getStatusCode() < HttpURLConnection.HTTP_OK
            || status.getStatusCode() >= HttpURLConnection.HTTP_MULT_CHOICE) {
        if (retval != null) {
            throw new ImageException(new String(retval));
        } else {
            throw new ImageException("Communication with print service '" + imageUrl + "' failed."
                    + "\nNo response from print service.");
        }
    }
    return retval;
}

From source file:com.wudaosoft.net.httpclient.DefaultHostConfig.java

public DefaultHostConfig() {
    defaultRequestConfig = RequestConfig.custom().setExpectContinueEnabled(false)
            // .setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setConnectionRequestTimeout(500)
            .setConnectTimeout(10000).setSocketTimeout(10000).build();
}

From source file:eu.redzoo.article.javaworld.stability.RestServicesTest.java

@BeforeClass
public static void setUp() throws Exception {

    server = new Tomcat();
    server.setPort(9080);/*from   w  w  w.  ja  v a2 s .c  o  m*/
    server.addWebapp("/service", new File("src/main/resources/webapp").getAbsolutePath());

    server.start();

    ClientConfig clientConfig = new ClientConfig(); // jersey specific
    clientConfig.connectorProvider(new ApacheConnectorProvider()); // jersey specific

    RequestConfig reqConfig = RequestConfig.custom() // apache HttpClient specific
            .build();

    clientConfig.property(ApacheClientProperties.REQUEST_CONFIG, reqConfig); // jersey specific

    client = ClientBuilder.newClient(clientConfig);

    HttpClientBuilder.create().setMaxConnPerRoute(30).setMaxConnTotal(150).setDefaultRequestConfig(reqConfig)
            .build();
}

From source file:org.riotfamily.linkcheck.HttpStatusChecker.java

public HttpStatusChecker() {
    RequestConfig config = RequestConfig.custom()
            .setConnectionRequestTimeout((int) FormatUtils.parseMillis("2s"))
            .setSocketTimeout((int) FormatUtils.parseMillis("5s")).setStaleConnectionCheckEnabled(true).build();

    client = HttpClients.custom().setDefaultRequestConfig(config).build();
}

From source file:qhindex.servercomm.ServerDataCache.java

public JSONObject sendRequest(JSONObject data, String url, boolean sentAdminNotification) {
    JSONObject obj = new JSONObject();

    final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(AppHelper.connectionTimeOut)
            .setConnectionRequestTimeout(AppHelper.connectionTimeOut)
            .setSocketTimeout(AppHelper.connectionTimeOut).setStaleConnectionCheckEnabled(true).build();
    final CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
    HttpPost httpPost = new HttpPost(url);

    String dataStr = data.toJSONString();
    dataStr = dataStr.replaceAll("null", "\"\"");

    if (sentAdminNotification == true) {
        try {//from  w  ww .j ava 2s  .co m
            AdminMail adminMail = new AdminMail();
            adminMail.sendMailToAdmin("Data to send to the server.", dataStr);
        } catch (Exception ex) { // Catch any problem during this step and continue 
            Debug.print("Could not send admin notification e-mail: " + ex);
        }
    }
    Debug.print("DATA REQUEST: " + dataStr);
    StringEntity jsonData = new StringEntity(dataStr, ContentType.create("plain/text", Consts.UTF_8));
    jsonData.setChunked(true);
    httpPost.addHeader("content-type", "application/json");
    httpPost.addHeader("accept", "application/json");
    httpPost.setEntity(jsonData);

    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() >= 300) {
            Debug.print("Exception while sending http request: " + statusLine.getStatusCode() + " : "
                    + statusLine.getReasonPhrase());
            resultsMsg += "Exception while sending http request: " + statusLine.getStatusCode() + " : "
                    + statusLine.getReasonPhrase() + "\n";
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String output = new String();
        String line;
        while ((line = br.readLine()) != null) {
            output += line;
        }
        output = output.substring(output.indexOf('{'));
        try {
            obj = (JSONObject) new JSONParser().parse(output);
        } catch (ParseException pEx) {
            Debug.print(
                    "Could not parse internet response. It is possible the cache server fail to deliver the content: "
                            + pEx.toString());
            resultsMsg += "Could not parse internet response. It is possible the cache server fail to deliver the content.\n";
        }
    } catch (IOException ioEx) {
        Debug.print("Could not handle the internet request: " + ioEx.toString());
        resultsMsg += "Could not handle the internet request.\n";
    }
    return obj;
}