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:org.jirban.jira.LoginData.java

public LoginData(String username, String password) {
    this.username = username;
    this.password = password;
    HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    HttpClient httpClient = HttpClientBuilder.create().build();
    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
    this.clientBuilder = ((ResteasyClientBuilder) ClientBuilder.newBuilder()).httpEngine(engine);

}

From source file:io.apiman.manager.api.gateway.rest.RestGatewayLink.java

/**
 * Constructor./* w  ww. j a v a2 s  .c  o m*/
 * @param gateway
 */
public RestGatewayLink(final GatewayBean gateway) {
    try {
        this.gateway = gateway;
        String cfg = gateway.getConfiguration();
        setConfig((RestGatewayConfigBean) mapper.reader(RestGatewayConfigBean.class).readValue(cfg));
        httpClient = HttpClientBuilder.create().addInterceptorFirst(new HttpRequestInterceptor() {
            @Override
            public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                configureBasicAuth(request);
            }
        }).build();
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.googlesource.gerrit.plugins.github.oauth.PooledHttpClientProvider.java

@Override
public HttpClient get() {
    HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnPerRoute(maxConnectionPerRoute)
            .setMaxConnTotal(maxTotalConnection);

    if (proxy.getProxyUrl() != null) {
        URL url = proxy.getProxyUrl();
        builder.setProxy(new HttpHost(url.getHost(), url.getPort()));
        if (!Strings.isNullOrEmpty(proxy.getUsername()) && !Strings.isNullOrEmpty(proxy.getPassword())) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(proxy.getUsername(),
                    proxy.getPassword());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()), creds);
            builder.setDefaultCredentialsProvider(credsProvider);
            builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
        }//from   ww  w .ja  v  a2 s .  c  om
    }

    return builder.build();
}

From source file:com.king.ess.gsa.GSAFeedForm.java

/**
 * It sends XML with feeds to GSA using proper form:
 * /* w  w  w.  j a  va2s . c om*/
 * @param xmlDocument  GSADocumentFormatter containing XML Document information
 * 
 * @return Was posted Ok?
 */
public boolean sendForm(GSADocumentFormatter xmlDocument) {
    boolean bSent = false;

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

    try {
        HttpPost postPageRequest;
        postPageRequest = new HttpPost(this.gsaServer);
        InputStream is = xmlDocument.writeToInputStream();

        // Add Form parameters
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        builder.addTextBody(FEEDTYPE_PARAM, xmlDocument.getFeedType(), ContentType.TEXT_PLAIN);
        builder.addTextBody(DATASOURCE_PARAM, xmlDocument.getDatasource(), ContentType.TEXT_PLAIN);
        builder.addBinaryBody(XMLFILE_PARAM, is);
        HttpEntity multipartEntity = builder.build();

        postPageRequest.setEntity(multipartEntity);

        HttpResponse postPageResponse = client.execute(postPageRequest);
        int status = postPageResponse.getStatusLine().getStatusCode();

        if (!(bSent = (status == 200)))
            log.error("GitHub API (" + this.gsaServer + ") returned " + status);
        else
            log.info("XML For datasource '" + xmlDocument.getDatasource() + "' and FeedType '"
                    + xmlDocument.getFeedType() + "' was posted successfully to GSA!!");

    } catch (Exception e) {
        log.error("Exception " + e.getMessage() + " in HTTP request " + this.gsaServer);
    }
    return bSent;
}

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  a  v  a 2 s.co m

    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:ch.icclab.cyclops.publish.APICaller.java

/**
 * Perform POST query and return Response
 * @param endpoint to be called/*from w ww  . j a  v  a  2s. c  o  m*/
 * @param object to be passed
 * @return Response object
 * @throws Exception
 */
public APICaller.Response post(URL endpoint, Object object) throws Exception {
    // prepare connection
    HttpClient client = HttpClientBuilder.create().build();

    // create request
    HttpPost request = new HttpPost(endpoint.toURI());
    StringEntity entity = new StringEntity(new Gson().toJson(object));
    request.addHeader("Accept", "application/json");
    request.addHeader("Content-Type", "application/json");
    request.setEntity(entity);

    // execute response
    HttpResponse response = client.execute(request);
    return new Response(IOUtils.toString(response.getEntity().getContent()),
            response.getStatusLine().getStatusCode());
}

From source file:MainFrame.HttpCommunicator.java

public void setCombos(JComboBox comboGroups, JComboBox comboDates, LessonTableModel tableModel)
        throws MalformedURLException, IOException {
    BufferedReader in = null;//from w w  w . jav a 2s  .  c om
    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:com.temenos.useragent.generic.http.DefaultHttpClient.java

@Override
public HttpResponse post(String url, HttpRequest request) {
    logHttpRequest(url, request);
    CloseableHttpClient client = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(DefaultHttpClientHelper.getBasicCredentialProvider()).build();
    HttpPost postRequest = new HttpPost(url);
    DefaultHttpClientHelper.buildRequestHeaders(request, postRequest);
    postRequest.setEntity(new StringEntity(request.payload(), "UTF-8"));
    try {/*from   w w w . j av a2s. c o m*/
        CloseableHttpResponse httpResponse = client.execute(postRequest);
        HttpEntity responseEntity = httpResponse.getEntity();
        return handleResponse(httpResponse, responseEntity);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.keycloak.testsuite.account.AccountRestServiceTest.java

@Before
public void before() {
    client = HttpClientBuilder.create().build();
}

From source file:it.govpay.web.console.utils.HttpClientUtils.java

public static HttpResponse getEsitoPagamento(String urlToInvoke, Logger log) throws Exception {
    HttpResponse responseGET = null;//from w w w.  java  2  s  .  c  o  m
    try {
        log.debug("Richiesta Esito del pagamento in corso...");

        URL urlObj = new URL(urlToInvoke);
        HttpHost target = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol());
        CloseableHttpClient client = HttpClientBuilder.create().disableRedirectHandling().build();
        HttpGet richiestaPost = new HttpGet();

        richiestaPost.setURI(urlObj.toURI());

        log.debug("Invio tramite client Http in corso...");
        responseGET = client.execute(target, richiestaPost);

        if (responseGET == null)
            throw new NullPointerException("La Response HTTP e' null");

        log.debug("Invio tramite client Http completato.");
        return responseGET;
    } catch (Exception e) {
        log.error("Errore durante l'invio della richiesta di pagamento: " + e.getMessage(), e);
        throw e;
    }
}