Example usage for org.apache.http.impl.client HttpClientBuilder create

List of usage examples for org.apache.http.impl.client HttpClientBuilder create

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder create.

Prototype

public static HttpClientBuilder create() 

Source Link

Usage

From source file:com.codota.uploader.Uploader.java

public Uploader(String codotaEndpoint, String token) {
    this.endpoint = codotaEndpoint;
    this.httpClient = HttpClientBuilder.create().build();
    this.token = token;
}

From source file:coolmapplugin.util.HTTPRequestUtil.java

public static String executeGet(String targetURL) {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

        HttpGet request = new HttpGet(targetURL);

        HttpResponse result = httpClient.execute(request);

        // TODO if there exists any other 20*
        if (result.getStatusLine().getStatusCode() != 200) {
            return null;
        }/*from ww w. jav a  2 s. com*/

        String jsonResult = EntityUtils.toString(result.getEntity(), "UTF-8");

        return jsonResult;

    } catch (IOException e) {
        return null;
    }
}

From source file:org.jboss.forge.website.service.Downloader.java

public String download(String url) throws IllegalStateException {
    String content = getContentFromCache(url);

    if (content == null) {

        try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
            HttpGet get = new HttpGet(url);
            HttpResponse response = client.execute(get);

            if (response.getStatusLine().getStatusCode() == 200)
                content = Streams.toString(response.getEntity().getContent());

            if (response.getStatusLine().getStatusCode() / 10 == 20)
                cache.put(url, new CacheEntry(url, content, System.currentTimeMillis()));

            else//w w  w.  ja va 2  s  .  co m
                throw new IllegalStateException("failed! (server returned status code: "
                        + response.getStatusLine().getStatusCode() + ")");
        } catch (IllegalStateException e) {
            throw e;
        } catch (Exception e) {
            throw new IllegalStateException("Failed to download: " + url, e);
        }

    }

    if (content == null) {
        content = getContentFromCacheUnrestricted(url);
    }

    return content;
}

From source file:no.digipost.api.useragreements.client.Examples.java

public void instantiate_client() {
    InputStream key = getClass().getResourceAsStream("certificate.p12");

    HttpHost proxy = new HttpHost("proxy.example.com", 8080, "http");

    final BrokerId brokerId = BrokerId.of(1234L);

    DigipostUserAgreementsClient client = new DigipostUserAgreementsClient.Builder(brokerId, key, "password")
            .useProxy(proxy) //optional
            .setHttpClientBuilder(HttpClientBuilder.create()) //optional
            .serviceEndpoint(URI.create("https://api.digipost.no")) //optional
            .build();// w  ww  . j  a  v a2 s  .  c o m
}

From source file:com.cybozu.kintone.gpsPunch.GpsPunchRequestManager.java

public GpsPunchRequestManager() {
    // ???//w w  w . ja  v  a  2s  .  c  om
    try {
        ResourceBundle rb = ResourceBundle.getBundle("gpspunch");
        authorization = rb.getString("authorization");
        companyId = rb.getString("companyid");
        target = rb.getString("target");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
    // HTTP Client??
    List<Header> headers = new ArrayList<Header>();
    headers.add(new BasicHeader("Authorization", authorization));
    // HTTP Client??
    this.httpClient = HttpClientBuilder.create().setDefaultHeaders(headers).build();
}

From source file:com.ibm.ra.remy.web.utils.BusinessRulesUtils.java

/**
 * Invoke Business Rules with JSON content
 *
 * @param content The payload of itineraries to send to Business Rules.
 * @return A JSON string representing the output of Business Rules.
 *//*from w  w w .  j a  va2  s  .c  o m*/
public static String invokeRulesService(String json) throws Exception {
    PropertiesReader constants = PropertiesReader.getInstance();
    String username = constants.getStringProperty(USERNAME_KEY);
    String password = constants.getStringProperty(PASSWORD_KEY);
    String endpoint = constants.getStringProperty(EXECUTION_REST_URL_KEY)
            + constants.getStringProperty(RULE_APP_PATH_KEY);

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(credentialsProvider).build();

    String responseString = "";

    try {
        HttpPost httpPost = new HttpPost(endpoint);
        httpPost.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
        StringEntity jsonEntity = new StringEntity(json, MessageUtils.ENCODING);
        httpPost.setEntity(jsonEntity);
        CloseableHttpResponse response = httpClient.execute(httpPost);

        try {
            HttpEntity entity = response.getEntity();
            responseString = EntityUtils.toString(entity, MessageUtils.ENCODING);
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpClient.close();
    }
    return responseString;
}

From source file:ar.edu.ubp.das.src.chat.actions.ValidAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpPost httpPost = new HttpPost("http://25.136.78.82:8080/login/");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("nombre_usuario", form.getItem("user")));
        params.add(new BasicNameValuePair("password", form.getItem("pw")));
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        CloseableHttpResponse postResponse = httpClient.execute(httpPost);

        HttpEntity responseEntity = postResponse.getEntity();
        StatusLine responseStatus = postResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            System.out.println(restResp);
            throw new RuntimeException("Los datos ingresados son incorrectos");
        }//w  w w .jav  a 2  s . c  om

        Header authHeader = postResponse.getFirstHeader("Auth-Token");
        String headerValue = authHeader != null ? authHeader.getValue() : "";

        HttpPost adminPost = new HttpPost("http://25.136.78.82:8080/login/admin");
        adminPost.addHeader("Authorization", "BEARER " + headerValue);
        adminPost.addHeader("accept", "application/json");

        postResponse = httpClient.execute(adminPost);
        responseEntity = postResponse.getEntity();
        responseStatus = postResponse.getStatusLine();

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException("Accesso restringido a Administradores");
        }

        request.getSession().setAttribute("user", restResp);
        request.getSession().setAttribute("token", headerValue);
        request.getSession().setAttribute("login_tmst", String.valueOf(System.currentTimeMillis()));

        return mapping.getForwardByName("success");

    } catch (IOException | RuntimeException e) {
        request.setAttribute("message", "Error al realizar login: " + e.getMessage());
        response.setStatus(401);
        return mapping.getForwardByName("failure");
    }
}

From source file:org.meteogroup.jbrotli.httpclient.apache.HttpClientExample.java

public String downloadFileAsString(String url) throws IOException {
    BrotliLibraryLoader.loadBrotli();//from  w  w  w. j a  v  a 2 s. c o  m
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.addInterceptorFirst(httpRequestInterceptor);
    httpClientBuilder.addInterceptorFirst(httpResponseInterceptor);
    try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
        String entity = downloadFileAsString(httpClient, url);
        if (entity != null)
            return entity;
    }
    return null;
}

From source file:com.gs.tools.doc.extractor.core.DownloadManager.java

private DownloadManager() {
    logger.info("Init DownloadManager");
    cookieStore = new BasicCookieStore();
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultCookieStore(cookieStore);

    Collection<Header> headers = new ArrayList<Header>();
    headers.add(new BasicHeader("Accept",
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"));
    headers.add(new BasicHeader("User-Agent",
            "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate,sdch"));
    headers.add(new BasicHeader("Accept-Language", "en-US,en;q=0.8"));
    //        headers.add(new BasicHeader("Accept-Encoding", 
    //                "gzip,deflate,sdch"));
    clientBuilder.setDefaultHeaders(headers);

    ConnectionConfig.Builder connectionConfigBuilder = ConnectionConfig.custom();
    connectionConfigBuilder.setBufferSize(10485760);
    clientBuilder.setDefaultConnectionConfig(connectionConfigBuilder.build());

    SocketConfig.Builder socketConfigBuilder = SocketConfig.custom();
    socketConfigBuilder.setSoKeepAlive(true);
    socketConfigBuilder.setSoTimeout(3000000);
    clientBuilder.setDefaultSocketConfig(socketConfigBuilder.build());
    logger.info("Create HTTP Client");
    httpClient = clientBuilder.build();/*from  w  ww .  ja  v a 2  s .co  m*/

}

From source file:com.example.analytics.AnalyticsServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    String trackingId = System.getenv("GA_TRACKING_ID");
    HttpClient client = HttpClientBuilder.create().build();
    URIBuilder builder = new URIBuilder();
    builder.setScheme("http").setHost("www.google-analytics.com").setPath("/collect").addParameter("v", "1") // API Version.
            .addParameter("tid", trackingId) // Tracking ID / Property ID.
            // Anonymous Client Identifier. Ideally, this should be a UUID that
            // is associated with particular user, device, or browser instance.
            .addParameter("cid", "555").addParameter("t", "event") // Event hit type.
            .addParameter("ec", "example") // Event category.
            .addParameter("ea", "test action"); // Event action.
    URI uri = null;/*from   w  ww .j  a v a  2 s .  c  o m*/
    try {
        uri = builder.build();
    } catch (URISyntaxException e) {
        throw new ServletException("Problem building URI", e);
    }
    HttpPost request = new HttpPost(uri);
    client.execute(request);
    resp.getWriter().println("Event tracked.");
}