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.wise.vle.domain.webservice.crater.CRaterHttpClient.java

/**
 * Handles POSTing a CRater Request to the CRater Servlet and returns the 
 * CRater response string./*  w ww .  j  ava  2  s .c om*/
 * 
 * @param cRaterUrl the CRater url
 * @param bodyData the xml body data to be sent to the CRater server
 * @return the response from the CRater server
 */
public static String post(String cRaterUrl, String bodyData) {
    String responseString = null;

    if (cRaterUrl != null) {
        HttpClient client = HttpClientBuilder.create().build();

        // Create a method instance.
        HttpPost post = new HttpPost(cRaterUrl);

        try {
            //System.out.println("CRater request bodyData:" + bodyData);
            post.setEntity(new StringEntity(bodyData, ContentType.TEXT_XML));

            // Execute the method.
            HttpResponse response = client.execute(post);

            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                System.err.println("Method failed: " + response.getStatusLine());
            }

            // Read the response body.
            responseString = IOUtils.toString(response.getEntity().getContent());
            //System.out.println("responseString: " + responseString);
        } catch (IOException e) {
            System.err.println("Fatal transport error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // Release the connection.
            post.releaseConnection();
        }
    }

    return responseString;
}

From source file:uk.org.openeyes.oink.it.ITSupport.java

public static IGenericClient buildHapiClientForProxy(Properties proxyProps) {
    // See if Patient exists
    String proxyUri = (String) proxyProps.get("proxy.uri");

    // Create a context and get the client factory so it can be configured
    FhirContext ctx = new FhirContext();
    IRestfulClientFactory clientFactory = ctx.getRestfulClientFactory();

    // Create an HTTP Client Builder
    HttpClientBuilder builder = HttpClientBuilder.create();

    // This interceptor adds HTTP username/password to every request
    String username = (String) proxyProps.get("proxy.username");
    String password = (String) proxyProps.get("proxy.password");
    builder.addInterceptorFirst(new HttpBasicAuthInterceptor(username, password));

    builder.addInterceptorFirst(new HttpRequestInterceptor() {

        @Override/*from  w ww  .ja v  a2s.  c  o m*/
        public void process(HttpRequest req, HttpContext context) throws HttpException, IOException {
            req.addHeader("Accept", "application/json+fhir; charset=UTF-8");
        }
    });

    // Use the new HTTP client builder
    clientFactory.setHttpClient(builder.build());

    IGenericClient client = clientFactory.newGenericClient("http://" + proxyUri);

    return client;
}

From source file:org.openbaton.nfvo.core.events.senders.RestEventSender.java

@Override
@Async//w w  w  .j  a v a  2s .  c  om
public Future<Void> send(EventEndpoint endpoint, ApplicationEventNFVO event) {
    try {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        Gson mapper = new GsonBuilder().create();
        String json = "{\"action\":\"" + event.getAction() + "\",\"payload\":"
                + mapper.toJson(event.getPayload()) + "}";

        log.trace("body is: " + json);

        log.trace("Invoking POST on URL: " + endpoint.getEndpoint());
        HttpPost request = new HttpPost(endpoint.getEndpoint());
        request.addHeader("content-type", "application/json");
        request.addHeader("accept", "application/json");
        StringEntity params = new StringEntity(json);
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
    } catch (Exception ignored) {
        log.warn("Impossible to reach the endpoint with name: " + endpoint.getName() + " via rest POST at url:"
                + endpoint.getEndpoint());
    }
    return new AsyncResult<>(null);
}

From source file:co.freeside.betamax.httpclient.BetamaxRequestDirector.java

public BetamaxRequestDirector(final RequestDirector delegate, Configuration configuration, Recorder recorder,
        CredentialsProvider credentialsProvider) {
    this.delegate = delegate;
    this.configuration = configuration;

    HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
            .useSystemProperties().build();
    handlerChain = new DefaultHandlerChain(recorder, httpClient);
}

From source file:com.wichita.edu.crawler.GerritHttpRequest.java

public GerritHttpRequest(String url) throws JSONException

{

    try {// w w w . j  a v a 2 s . co m

        System.out.println(url);
        //sending an httprequest with GET method and get result by httpEntity
        HttpClient httpclient = HttpClientBuilder.create().build();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;
        HttpGet httpGet = new HttpGet(url);
        httpResponse = httpclient.execute(httpGet);
        httpEntity = httpResponse.getEntity();
        String response = EntityUtils.toString(httpEntity);
        System.out.println(response);
        //if response be empty the length of response is 8.
        if (response.length() > 8) {
            //JSON response has )]} extra characters which should be remove.
            response = response.replace(")]}'", "");

            //response from this url:"https://git.eclipse.org/r/changes/?q=mylyn&o=ALL_REVISIONS&o=ALL_FILES&o=MESSAGES";
            if (response.startsWith("\n[")) {
                //declare JSONArray from response 
                reviewDataArray = new JSONArray(response);
                if (reviewDataArray.length() > 1) {
                    //declare JSONObject from reviewDataArray
                    reviewDataObject = reviewDataArray.getJSONObject(1);
                } else {
                    //declare JSONObject from reviewDataArray
                    reviewDataObject = reviewDataArray.getJSONObject(0);
                }

            }
            //response from this url:""https://git.eclipse.org/r/changes/"+entry.getKey()+"/revisions/"+value+"/comments"
            else if (response.startsWith("\n{")) {
                reviewDataObject = new JSONObject(response);
                // System.out.println(response.toString());
            }

        }

    }

    catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:org.apache.ambari.view.internal.WSProvider.java

private ClientHttpRequestFactory getClientHttpRequestFactory() {
    int timeout = 5000;
    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
    CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    return new HttpComponentsClientHttpRequestFactory(client);
}

From source file:org.wildfly.swarm.jaxrs.SimpleHttp.java

protected Response getUrlContents(String theUrl, boolean useAuth, boolean followRedirects) {

    StringBuilder content = new StringBuilder();
    int code;//from   ww w. ja va  2 s.co  m

    try {

        CredentialsProvider provider = new BasicCredentialsProvider();

        HttpClientBuilder builder = HttpClientBuilder.create();
        if (!followRedirects) {
            builder.disableRedirectHandling();
        }
        if (useAuth) {
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "password");
            provider.setCredentials(AuthScope.ANY, credentials);
            builder.setDefaultCredentialsProvider(provider);
        }
        HttpClient client = builder.build();

        HttpResponse response = client.execute(new HttpGet(theUrl));
        code = response.getStatusLine().getStatusCode();

        if (null == response.getEntity()) {
            throw new RuntimeException("No response content present");
        }

        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));

        String line;

        while ((line = bufferedReader.readLine()) != null) {
            content.append(line + "\n");
        }
        bufferedReader.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return new Response(code, content.toString());
}

From source file:com.trenurbanoapp.webapi.WebApiRestClient.java

private HttpClient getHttpClient() {
    if (httpClient == null) {
        httpClient = HttpClientBuilder.create().build();
    }
    return httpClient;
}

From source file:org.slf4j.impl.PiazzaLogger.java

/**
 * Initializes the logger component. This will scan the environment for the URL to Piazza Logger REST endpoint.
 */// ww w .j  a v a2s  .c  o  m
static void init() {
    if (INITIALIZED) {
        return;
    }
    INITIALIZED = true;
    // Scan the environment for the URL to Pz-Logger
    PZ_LOGGER_URL = System.getenv("logger.url");

    System.out.println(
            String.format("PiazzaLogger initialized for service %s, url: %s", "serviceName", PZ_LOGGER_URL));
    HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(7500).setMaxConnPerRoute(4000).build();
    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
}

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

@Override
public String getString(String url) throws Exception {
    url = convertURL(url);//w  w  w  . j  ava2 s. c o  m

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

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

    HttpClient httpClient = HttpClientBuilder.create().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());
}