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.esupportail.filex.web.WebController.java

@Autowired
public void setRestTemplate(RestTemplate restTemplate) {
    this.restTemplate = restTemplate;
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(50 * 1000)
            .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
    HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
    HttpComponentsClientHttpRequestFactory factory = (HttpComponentsClientHttpRequestFactory) restTemplate
            .getRequestFactory();//from  w  ww . ja v  a2 s  .  c o  m
    factory.setHttpClient(httpClient);
}

From source file:gui.EventAllReader.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/event_names.json?lang=" + this.language);

    HttpResponse response;//from ww  w  . j  av a2  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);

                    JSONArray array = (JSONArray) obj;

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

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

                        if (obj2.get("name") != null) {

                            this.result.put(obj2.get("id"), obj2.get("name"));
                        }
                    }

                    this.apimanager.updateToolTips();

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

                        request.releaseConnection();
                        Thread.sleep(5000);
                    } catch (InterruptedException ex1) {
                        Logger.getLogger(EventAllReader.class.getName()).log(Level.SEVERE, null, ex1);
                    }
                }
            } else {
                try {
                    request.releaseConnection();
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(EventAllReader.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } catch (IOException | IllegalStateException ex) {
            try {
                Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex);

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

                this.interrupt();
            }
        }
    }
}

From source file:RGSCommonUtils.UniversalConnectionInterfaceImp.java

@Override
public String GET_Request(String p_uri, Object... p_objects) throws IOException {
    HttpGet request = new HttpGet(p_uri);
    RequestConfig config;/*from  w w w. j  av a  2  s  .c o  m*/
    if (this.proxy != null)
        config = RequestConfig.custom().setProxy(this.proxy).build();
    else
        config = RequestConfig.custom().build();
    request.setConfig(config);

    CloseableHttpResponse response = httpClient.execute(request);
    //        ? 
    if (response.getStatusLine().getStatusCode() == 302) {
        String newUrl = response.getHeaders("Location")[0].getValue();
        //           ?? ?  (? ?)
        request = new HttpGet(newUrl.replace("https://", "http://"));
        request.setConfig(config);
        response = httpClient.execute(request);
    }

    return responceToString(response);
}

From source file:net.fischboeck.discogs.DiscogsClient.java

private void init() {
    HttpClientBuilder builder = HttpClients.custom();
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(REQUEST_TIMEOUT).build();

    this.httpClient = builder.setDefaultHeaders(this.getDefaultHeaders()).setDefaultRequestConfig(requestConfig)
            .build();//from   ww w.  ja  va2 s  . co m

    this.mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}

From source file:com.liferay.jenkins.tools.RemoteStringGetter.java

@Override
public String getString(String url) throws Exception {
    url = convertURL(url);/*from w w w. j ava2s .  c  om*/

    logger.debug("Fetching string from {}", url);

    CredentialsProvider provider = new BasicCredentialsProvider();

    Credentials credentials = new UsernamePasswordCredentials(username, password);

    provider.setCredentials(AuthScope.ANY, credentials);

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

    HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider)
            .setDefaultRequestConfig(requestConfig).build();

    HttpResponse httpResponse = httpClient.execute(new HttpGet(url));

    int statusCode = httpResponse.getStatusLine().getStatusCode();

    logger.debug("Successfully fetched {}", url);

    return IOUtils.toString(httpResponse.getEntity().getContent(), Charset.defaultCharset());
}

From source file:org.freaknet.gtrends.client.GoogleTrendsClientFactory.java

private static GoogleTrendsClient _parse(CmdLineParser cmdLine) throws GoogleTrendsClientRunException {
    setLogLevel(cmdLine);/*w  w w.  j  av  a2  s . c  o  m*/
    try {
        // TODO - Move outside
        // Prints all available regions and exists
        if (cmdLine.getPrintRegionsOpt()) {
            RegionParser.getInstance().printAll();
            System.exit(0);
        }

        // HTTP Client setup
        int timeout = 5; // seconds
        RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000)
                .setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
        _httpClient = HttpClientBuilder.create().setDefaultCookieStore(_cookieStore)
                .setDefaultRequestConfig(config)
                //.setRedirectStrategy(new LaxRedirectStrategy())
                .build();

        BasicClientCookie cookie = new BasicClientCookie("I4SUserLocale", "it");
        cookie.setVersion(0);
        cookie.setDomain("www.google.com");
        cookie.setPath("/trends");
        cookie.setSecure(false);
        _cookieStore.addCookie(cookie);

        cookie = new BasicClientCookie("PREF", "");
        cookie.setVersion(0);
        cookie.setDomain("www.google.com");
        cookie.setPath("/trends");
        cookie.setSecure(false);
        _cookieStore.addCookie(cookie);

        // TODO - fix proxy
        //      if (cmdLine.getProxyHostname() != null) {
        //        HttpHost proxyHost = new HttpHost(cmdLine.getProxyHostname(), cmdLine.getProxyPort(), cmdLine.getProxyProtocol());
        //        Credentials credentials = cmdLine.getProxyCredentials();
        //        if (credentials != null) {
        //          _httpClient.get
        //          _httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), credentials);
        //        }
        //        _httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
        //      }
        // Setup Google Authenticator
        _authenticator = new GoogleAuthenticator(cmdLine.getUsername(), cmdLine.getPassword(), _httpClient);

    } catch (FileNotFoundException ex) {
        throw new GoogleTrendsClientRunException(ex);
    }

    return new GoogleTrendsClient(_authenticator, _httpClient);
}

From source file:cn.wanghaomiao.seimi.http.hc.HttpClientFactory.java

public static HttpClientBuilder cliBuilder(int timeout) {
    HttpRequestRetryHandler retryHander = new HttpRequestRetryHandler() {
        @Override/*from  ww w  .  j  a  v a 2s .  c  om*/
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount > 3) {
                // Do not retry if over max retry count
                return false;
            }
            if (exception instanceof java.net.SocketTimeoutException) {
                //?
                return true;
            }
            if (exception instanceof InterruptedIOException) {
                // Timeout
                return true;
            }
            if (exception instanceof UnknownHostException) {
                // Unknown host
                return false;
            }

            if (exception instanceof SSLException) {
                // SSL handshake exception
                return false;
            }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                // Retry if the request is considered idempotent
                return true;
            }
            return false;
        }
    };
    RedirectStrategy redirectStrategy = new SeimiRedirectStrategy();
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout)
            .build();
    PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = HttpClientConnectionManagerProvider
            .getHcPoolInstance();
    return HttpClients.custom().setDefaultRequestConfig(requestConfig)
            .setConnectionManager(poolingHttpClientConnectionManager).setRedirectStrategy(redirectStrategy)
            .setRetryHandler(retryHander);
}

From source file:com.dnastack.bob.service.fetcher.util.HttpUtils.java

@PostConstruct
private void init() {
    RequestConfig config = RequestConfig.custom().setSocketTimeout(REQUEST_TIMEOUT * 1000)
            .setConnectTimeout(REQUEST_TIMEOUT * 1000).setConnectionRequestTimeout(REQUEST_TIMEOUT * 1000)
            .build();/*from  w  w  w  .j  av  a  2  s. c  o m*/
    httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
}

From source file:com.imagesleuth.imagesleuthclient2.Getter.java

public Getter(String url, String user, String password) {
    Test.testNull(url);//from www.  j a v  a 2  s .co m
    Test.testNull(user);
    Test.testNull(password);

    this.url = url;
    harray.add(new BasicHeader("Authorization",
            "Basic " + Base64.encodeBase64String((user + ":" + password).getBytes())));

    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, password);
    credsProvider.setCredentials(AuthScope.ANY, credentials);
    requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(30000).build();
}

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

@NotWorking
public void toggleCommentsEnabled() throws ScratchProjectException {
    final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

    final CookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
    final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", this.session.getSessionID());
    final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", this.session.getCSRFToken());
    final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
    lang.setDomain(".scratch.mit.edu");
    lang.setPath("/");
    sessid.setDomain(".scratch.mit.edu");
    sessid.setPath("/");
    token.setDomain(".scratch.mit.edu");
    token.setPath("/");
    debug.setDomain(".scratch.mit.edu");
    debug.setPath("/");
    cookieStore.addCookie(lang);/* w w  w. j  a v  a  2  s  . c  om*/
    cookieStore.addCookie(sessid);
    cookieStore.addCookie(token);
    cookieStore.addCookie(debug);

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

    final HttpUriRequest update = RequestBuilder.put()
            .setUri("https://scratch.mit.edu/site-api/comments/project/" + this.getProjectID()
                    + "/toggle-comments/")
            .addHeader("Accept", "*/*")
            .addHeader("Referer", "https://scratch.mit.edu/projects/" + this.getProjectID() + "/")
            .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")
            .addHeader("Cookie",
                    "scratchsessionsid=" + this.session.getSessionID() + "; scratchcsrftoken="
                            + this.session.getCSRFToken())
            .addHeader("X-CSRFToken", this.session.getCSRFToken()).build();
    try {
        resp = httpClient.execute(update);
        System.out.println("current status:" + resp.getStatusLine().getStatusCode());
        if (resp.getStatusLine().getStatusCode() != 200)
            throw new ScratchProjectException();
        final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

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

        System.out.println(result);
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }
}