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.geosamples.utilities.HTTPClient.java

/**
 * This method relaxes SSL constraints because geosamples does not yet
 * provide certificate.// w  w  w.  j a va  2 s .c  om
 *
 * @see <a href="http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/">Tom's Blog</a>
 * @return CloseableHttpClient
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.KeyStoreException
 * @throws java.security.KeyManagementException
 */
public static CloseableHttpClient clientWithNoSecurityValidation()
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    SSLContext sslContext = null;

    sslContext = new SSLContextBuilder().loadTrustMaterial(null, (X509Certificate[] arg0, String arg1) -> true)
            .build();

    clientBuilder.setSSLContext(sslContext);

    // don't check Hostnames, either.
    HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    clientBuilder.setConnectionManager(connMgr);

    CloseableHttpClient httpClient = clientBuilder.build();

    return httpClient;
}

From source file:com.ibm.watson.retrieveandrank.app.rest.UtilityFunctions.java

public static CloseableHttpClient createHTTPClient(URI uri, String username, String password) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
            new UsernamePasswordCredentials(username, password));
    return HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
            .addInterceptorFirst(new PreemptiveAuthInterceptor()).build();
}

From source file:org.sakaiproject.contentreview.urkund.util.UrkundAPIUtil.java

public static String postDocument(String baseUrl, String receiverAddress, String externalId,
        UrkundSubmission submission, String urkundUsername, String urkundPassword, int timeout) {
    String ret = null;//from w  w w.  j av  a2s  .  c  o m

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(timeout);
    requestBuilder = requestBuilder.setConnectionRequestTimeout(timeout);

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestBuilder.build());
    try (CloseableHttpClient httpClient = builder.build()) {

        HttpPost httppost = new HttpPost(baseUrl + "submissions/" + receiverAddress + "/" + externalId);
        //------------------------------------------------------------
        EntityBuilder eBuilder = EntityBuilder.create();
        eBuilder.setBinary(submission.getContent());

        httppost.setEntity(eBuilder.build());
        //------------------------------------------------------------
        if (StringUtils.isNotBlank(urkundUsername) && StringUtils.isNotBlank(urkundPassword)) {
            addAuthorization(httppost, urkundUsername, urkundPassword);
        }
        //------------------------------------------------------------
        httppost.addHeader("Accept", "application/json");
        httppost.addHeader("Content-Type", submission.getMimeType());
        httppost.addHeader("Accept-Language", submission.getLanguage());
        httppost.addHeader("x-urkund-filename", submission.getFilenameEncoded());
        httppost.addHeader("x-urkund-submitter", submission.getSubmitterEmail());
        httppost.addHeader("x-urkund-anonymous", Boolean.toString(submission.isAnon()));
        httppost.addHeader("x-urkund-subject", submission.getSubject());
        httppost.addHeader("x-urkund-message", submission.getMessage());
        //------------------------------------------------------------

        HttpResponse response = httpClient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {
            ret = EntityUtils.toString(resEntity);
            EntityUtils.consume(resEntity);
        }

    } catch (IOException e) {
        log.error("ERROR uploading File : ", e);
    }

    return ret;
}

From source file:com.comcast.cdn.traffic_control.traffic_router.neustar.data.HttpClient.java

public CloseableHttpResponse execute(HttpUriRequest request) {
    try {//w w w . j a v  a  2 s .com
        httpClient = HttpClientBuilder.create().build();
        return httpClient.execute(request);
    } catch (IOException e) {
        LOGGER.warn("Failed to execute http request " + request.getMethod() + " " + request.getURI() + ": "
                + e.getMessage());
        try {
            httpClient.close();
        } catch (IOException e1) {
            LOGGER.warn("After exception, Failed to close Http Client " + e1.getMessage());
        }
        return null;
    }
}

From source file:org.wso2.security.tools.scanner.dependency.js.utils.CommonApiInvoker.java

/**
 * Connect GitHub API//from   w  ww .  ja v  a 2 s.c  o  m
 *
 * @param url URL of API call.
 * @return Response String.
 * @throws ApiInvokerException Exception occurred while API Call.
 */
public static String connectGitAPI(String url) throws ApiInvokerException {
    HttpResponse response;
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(url);
    // add request header
    request.addHeader("User-Agent", USER_AGENT);
    request.addHeader("content-type", "application/json");

    /*
     * api request need to be authorized to get high api request per hour
     * Note: For unauthorized user request limit is 60 per hour
     * If authorized user request limit is 5000
     * But the private github access token expired once commit done, Need to get new access token
     */
    request.addHeader("Authorization", "Bearer " + new String(gitToken));
    StringBuffer result = null;
    BufferedReader bufferedReader = null;
    try {
        response = client.execute(request);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            bufferedReader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            result = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
        }
    } catch (IOException e) {
        throw new ApiInvokerException("Failed to connect Git API endpoint " + url, e);
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                log.error("Unable to close stream : ", e);
            }
        }

    }
    if (result != null) {
        return result.toString();
    } else {
        return null;
    }
}

From source file:io.github.theangrydev.thinhttpclient.apache.ApacheHttpClient.java

public static ApacheHttpClient apacheHttpClient() {
    return new ApacheHttpClient(HttpClientBuilder.create().build());
}

From source file:org.n52.sos.soe.HttpUtil.java

private static CloseableHttpClient createClient() {
    return HttpClientBuilder.create().build();
}

From source file:com.oracle.jes.samples.hellostorage.RegisterDevice.java

public String sendRecord(String m) {
    mode = false;//from   w w w.  ja  v  a2s. c  om
    String out = null;

    //   DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpClient httpclient = HttpClientBuilder.create().build();

    HttpPost httppostreq;
    if (!mode) {

        httppostreq = new HttpPost("http://192.168.1.5:8080/pichrony/RegNewChrony");

    } else {
        httppostreq = new HttpPost("http://security.netmaxjava.com/phlogin");

    }

    StringEntity se = null;

    try {
        se = new StringEntity(m);
    } catch (UnsupportedEncodingException ex) {
        //Logger.getLogger(RegisterDevice.class.getName()).log(Level.SEVERE, null, ex);
    }

    //   se.setContentType("application/json;");

    httppostreq.setEntity(se);

    try {
        HttpResponse respo = httpclient.execute(httppostreq);
        if (respo != null) {
            out = "";
            InputStream inputstream = respo.getEntity().getContent();
            out = convertStreamToString(inputstream);

        } else {

        }
    } catch (ClientProtocolException e) {

    } catch (IOException | IllegalStateException e) {
    }
    return out;
}

From source file:de.pubflow.server.core.restConnection.WorkflowSender.java

/**
 * Sends a post request to the Workflow engine to use a certain Workflow
 * specified through the given path.//from w ww. j av  a2s  . c  o  m
 * 
 * @param wfCall
 *            The message with all necessary informations to create a new
 *            Workflow
 * @param workflowPath
 *            The path for the specific Workflow to be used.
 * @throws WFRestException
 *             if the connection responses with a HTTP response code other
 *             than 2xx
 */
public static void initWorkflow(WorkflowRestCall wfCall, String workflowPath) throws WFRestException {
    Logger myLogger = LoggerFactory.getLogger(WorkflowSender.class);

    myLogger.info("Trying to use workflow on: " + workflowPath);
    Gson gson = new Gson();
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(workflowPath);
    HttpResponse response = null;

    try {
        StringEntity postingString = new StringEntity(gson.toJson(wfCall), ContentType.APPLICATION_JSON);

        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json;charset=utf-8");
        response = httpClient.execute(post);
        System.out.println(post.getURI());
        myLogger.info("Http response: " + response.toString());

    } catch (Exception e) {
        myLogger.error("Could not deploy new Workflow with ID: " + wfCall.getID());
        myLogger.error(e.toString());
        throw new WFRestException("Workflow could not be started");
    }
    if (response.getStatusLine().getStatusCode() >= 300) {
        throw new WFRestException(
                "The called WorkflowService send status code: " + response.getStatusLine().getStatusCode()
                        + " and error: " + response.getStatusLine().getReasonPhrase());
    }

}

From source file:backend.translator.GTranslator.java

private File downloadFile(String url) throws IOException {
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(url);
    request.addHeader("User-Agent", "Mozilla/5.0");
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    BufferedInputStream bis = new BufferedInputStream(entity.getContent());
    File f = new File(R.TRANS_RESULT_PATH);
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
    int inByte;//from   w w  w . j  ava2  s.co  m
    while ((inByte = bis.read()) != -1)
        bos.write(inByte);

    bis.close();
    bos.close();
    return f;
}