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:org.frontcache.agent.FrontCacheAgent.java

public FrontCacheAgent(String frontcacheURL) {
    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(3000)
            .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();

    ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {
        @Override/*from w w w .  j ava 2s  .com*/
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            return 10 * 1000;
        }
    };

    client = HttpClients.custom().setDefaultRequestConfig(requestConfig)
            .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
            .setKeepAliveStrategy(keepAliveStrategy).setRedirectStrategy(new RedirectStrategy() {
                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    return false;
                }

                @Override
                public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response,
                        HttpContext context) throws ProtocolException {
                    return null;
                }
            }).build();

    this.frontCacheURL = frontcacheURL;

    if (frontcacheURL.endsWith("/"))
        this.frontCacheURI = frontcacheURL + IO_URI;
    else
        this.frontCacheURI = frontcacheURL + "/" + IO_URI;
}

From source file:counsil.WebClient.java

public String getFromURL(String ip, int port, String URL) throws IOException {
    String outString = "";

    Integer portInt = port;/*  w  w  w .ja v a  2  s.  c  om*/
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2 * 1000).build();

    CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
    BasicConfigurator.configure();

    try {
        HttpGet httpget = new HttpGet("http://" + ip + ":" + portInt.toString() + URL);

        // Create a custom response handler
        ResponseHandler<String> responseHandler = (HttpResponse response) -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        };
        String responseBody = httpclient.execute(httpget, responseHandler);
        outString = responseBody;
    } finally {
        httpclient.close();
    }

    return outString;
}

From source file:edu.mit.scratch.ScratchStatistics.java

protected static JSONObject getStatisticsJSONObject() throws ScratchStatisticalException {
    try {/*from   www  .  j a va  2 s  . c om*/
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
        debug.setDomain(".scratch.mit.edu");
        debug.setPath("/");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        cookieStore.addCookie(debug);
        cookieStore.addCookie(lang);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/statistics/data/daily/")
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest").build();
        try {
            resp = httpClient.execute(update);
        } catch (final IOException e) {
            e.printStackTrace();
            throw new ScratchStatisticalException();
        }

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException e) {
            e.printStackTrace();
            throw new ScratchStatisticalException();
        }

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        return new JSONObject(result.toString().trim());
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new ScratchStatisticalException();
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchStatisticalException();
    }
}

From source file:org.thoughtcrime.securesms.mms.OutgoingMmsConnection.java

@Override
protected HttpUriRequest constructRequest(boolean useProxy) throws IOException {
    HttpPostHC4 request = new HttpPostHC4(apn.getMmsc());
    request.addHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic");
    request.addHeader("x-wap-profile", "http://www.google.com/oha/rdf/ua-profile-kila.xml");
    request.addHeader("Content-Type", "application/vnd.wap.mms-message");
    request.setEntity(new ByteArrayEntityHC4(mms));
    if (useProxy) {
        HttpHost proxy = new HttpHost(apn.getProxy(), apn.getPort());
        request.setConfig(RequestConfig.custom().setProxy(proxy).build());
    }// w w  w . j a  v  a2  s .  c om
    return request;
}

From source file:com.linemetrics.monk.api.ApiClient.java

public ApiClient(String uri, ICredentials creds) throws RestException {

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(OPERATION_TIME_OUT)
            .setConnectionRequestTimeout(CONNECTION_TIME_OUT).setSocketTimeout(SOCKET_TIME_OUT).build();
    HttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();

    restclient = new RestClient(httpclient, creds, URI.create(uri));

    creds.initialize(this);
}

From source file:eu.redzoo.article.javaworld.stability.service.payment.SyncPaymentService.java

public SyncPaymentService() {
    ClientConfig clientConfig = new ClientConfig(); // jersey specific
    clientConfig.connectorProvider(new ApacheConnectorProvider()); // jersey
    // specific/*  w w  w .  j a  v  a2s  . c om*/

    RequestConfig reqConfig = RequestConfig.custom()
            // apache HttpClient specific
            .setConnectTimeout(1000).setSocketTimeout(1000).setConnectionRequestTimeout(100).build();

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

    client = ClientBuilder.newClient(clientConfig);
    client.register(new ClientCircutBreakerFilter());

    paymentDao = new PaymentDaoImpl();
}

From source file:com.tingtingapps.securesms.mms.IncomingLegacyMmsConnection.java

private HttpUriRequest constructRequest(Apn contentApn, boolean useProxy) throws IOException {
    HttpGetHC4 request = new HttpGetHC4(contentApn.getMmsc());
    for (Header header : getBaseHeaders()) {
        request.addHeader(header);/*from   w w w.j av a  2 s  .c o m*/
    }
    if (useProxy) {
        HttpHost proxy = new HttpHost(contentApn.getProxy(), contentApn.getPort());
        request.setConfig(RequestConfig.custom().setProxy(proxy).build());
    }
    return request;
}

From source file:com.match_tracker.twitter.TwitterSearch.java

public TwitterSearch(URL twitterSearchAuthUrl) throws MalformedURLException {
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
    HttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
    Unirest.setHttpClient(httpclient);/*  w w w.  j a  v  a2s .c o m*/

    this.twitterSearchURL = new URL(twitterSearchAuthUrl, SEARCH_API);
}

From source file:zz.pseas.ghost.login.weibo.SinaWeiboLogin.java

public static String getSinaCookie(String username, String password) throws Exception {

    StringBuilder sb = new StringBuilder();
    HtmlUnitDriver driver = new HtmlUnitDriver(true);
    // driver.setSocksProxy("127.0.0.1", 1080);
    // driver.setProxy("127.0.0.1", 1080);
    // HtmlOption htmlOption=new Ht
    // WebDriver driver = new FirefoxDriver();
    driver.setJavascriptEnabled(true);/*from ww w.  j  a  va2s . c o  m*/
    // user agent switcher//
    String loginAddress = "http://login.weibo.cn/login/";
    driver.get(loginAddress);
    WebElement ele = driver.findElementByCssSelector("img");
    String src = ele.getAttribute("src");
    String cookie = concatCookie(driver);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(1000)
            .setCookieSpec(cookie).build();

    HttpGet httpget = new HttpGet(src);
    httpget.setConfig(requestConfig);
    CloseableHttpResponse response = httpclient.execute(httpget);

    HttpEntity entity;
    String result = null;
    try {

        if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
            // try again//
        }
        entity = response.getEntity();

        if (entity != null) {
            InputStream instream = entity.getContent();
            try {
                // do something useful
                InputStream inputStream = entity.getContent();
                BufferedImage img = ImageIO.read(inputStream);
                // deal with the weibo captcha //
                String picName = LoginUtils.getCurrentTime("yyyyMMdd-hhmmss");
                // captcha//
                LoginUtils.getCaptchaDir();
                picName = "./captcha/captcha-" + picName + ".png";
                ImageIO.write(img, "png", new File(picName));
                String userInput = new CaptchaFrame(img).getUserInput();
                WebElement mobile = driver.findElementByCssSelector("input[name=mobile]");
                mobile.sendKeys(username);
                WebElement pass = driver.findElementByCssSelector("input[name^=password]");
                pass.sendKeys(password);
                WebElement code = driver.findElementByCssSelector("input[name=code]");
                code.sendKeys(userInput);
                WebElement rem = driver.findElementByCssSelector("input[name=remember]");
                rem.click();
                WebElement submit = driver.findElementByCssSelector("input[name=submit]");
                // ?//
                submit.click();
                result = concatCookie(driver);
                driver.close();
            } finally {
                instream.close();
            }
        }
    } finally {
        response.close();
    }

    if (result.contains("gsid_CTandWM")) {
        return result;
    } else {
        // throw new Exception("weibo login failed");
        return null;
    }
}

From source file:gui.WvWMatchReader.java

@Override
public void run() {

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 1000).build();
    HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
    //HttpClient client = new DefaultHttpClient();

    HttpGet request = new HttpGet("https://api.guildwars2.com/v1/wvw/matches.json");

    HttpResponse response;/*from  w w w . java  2  s.c o m*/

    String line = "";
    String out = "";

    while (!this.isInterrupted()) {

        try {

            response = client.execute(request);

            if ((response.getStatusLine().toString().contains("200"))) {

                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")));

                line = "";
                out = "";

                while ((line = rd.readLine()) != null) {

                    out = out + line;
                }

                JSONParser parser = new JSONParser();

                Object obj;

                this.result.clear();

                try {

                    obj = parser.parse(out);

                    JSONObject obj2 = (JSONObject) obj;
                    JSONArray array = (JSONArray) obj2.get("wvw_matches");

                    for (int i = 0; i < array.size(); i++) {

                        obj2 = (JSONObject) array.get(i);

                        this.result.put("" + obj2.get("wvw_match_id"),
                                new String[] { "" + obj2.get("red_world_id"), "" + obj2.get("blue_world_id"),
                                        "" + obj2.get("green_world_id") });
                    }

                    request.releaseConnection();

                    this.wvwCheckBox.setEnabled(true);
                    this.interrupt();
                } catch (ParseException ex) {
                    try {
                        Logger.getLogger(ApiManager.class.getName()).log(Level.SEVERE, null, ex);

                        request.releaseConnection();
                        Thread.sleep(3000);
                    } catch (InterruptedException ex1) {
                        Logger.getLogger(WvWMatchReader.class.getName()).log(Level.SEVERE, null, ex1);
                    }
                }
            } else {
                try {
                    Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, "Connection error.");

                    request.releaseConnection();
                    Thread.sleep(3000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(HomeWorldAllReader.class.getName()).log(Level.SEVERE, null, ex);

                    this.interrupt();
                }
            }
        } catch (IOException | IllegalStateException ex) {
            try {
                Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex);

                request.releaseConnection();
                Thread.sleep(3000);
            } catch (InterruptedException ex1) {
                Logger.getLogger(HomeWorldAllReader.class.getName()).log(Level.SEVERE, null, ex1);

                this.interrupt();
            }
        }
    }
}