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:communication.Communicator.java

/**
 * Adds a new trackingPosition to an existing cartracker
 *
 * @param tracker The cartracker with a new trackingPosition
 * @return The serialnumber of the new trackingPosition
 * @throws IOException/*from ww  w . j  a va  2  s .  c  o  m*/
 */
public static Long postTrackingPositionsForTracker(CarTracker tracker) throws IOException {
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(BASE_URL_PRODUCTION + "/" + tracker.getId() + "/movements");
    String jsonBody = gson.toJson(tracker.getCurrentTrackingPeriod());
    StringEntity postingString = new StringEntity(jsonBody, CHARACTER_SET);
    post.setEntity(postingString);
    post.setHeader(HTTP.CONTENT_TYPE, "application/json");
    HttpResponse response = httpClient.execute(post);

    String responseString = EntityUtils.toString(response.getEntity(), CHARACTER_SET);
    JSONObject json = new JSONObject(responseString);
    return json.getLong("serialNumber");
}

From source file:v2.service.generic.library.utils.HttpClientUtil.java

public static HttpClient createHttpClient() {
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 1000).build();
    CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
    return httpclient;
}

From source file:org.codehaus.mojo.license.utils.HttpRequester.java

/**
 * this method will send a simple GET-request to the given destination and will return the result as a
 * string/*from   w  ww  .  j  av  a 2 s.  c o  m*/
 * 
 * @param url the resource destination that is expected to contain pure text
 * @return the string representation of the resource at the given URL
 */
public static String getFromUrl(String url) throws MojoExecutionException {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpGet get = new HttpGet(url);
    CloseableHttpResponse response = null;

    String result = null;
    try {
        response = httpClient.execute(get);
        result = IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8"));
    } catch (ClientProtocolException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }
        }
    }
    return result;
}

From source file:com.sample.JavaHTTPResource.java

public static void init() {
    client = HttpClientBuilder.create().build();
    mfpHost = new HttpHost("mobilefirstplatform.ibmcloud.com", 443, "https");
    weatherHost = new HttpHost("twcservice.mybluemix.net", 80, "http");
}

From source file:hobbyshare.testclient.RestService_TestClient.java

public void test_Login() {
    HttpClient httpClient = HttpClientBuilder.create().build();

    JSONObject loginAttempt = new JSONObject();
    loginAttempt.put("password", "1234");
    loginAttempt.put("userName", "77_username");

    try {/* w w w. j a  v  a  2  s.  c  om*/
        HttpPost request = new HttpPost("http://localhost:8095/login");
        StringEntity params = new StringEntity(loginAttempt.toString());
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);

        System.out.println("---Testing Login----");
        System.out.println(response.toString());
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");
        System.out.println(responseString);
        System.out.println("----End of login Test----");
    } catch (Exception ex) {
        // handle exception here
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.autonomy.nonaci.indexing.impl.IndexingServiceImplTest.java

@Before
public void createIndexingServiceImpl() {
    final ServerDetails serverDetails = new ServerDetails();
    serverDetails.setHost("localhost");
    serverDetails.setPort(9901);//from   w w w .  java 2 s . c  om

    indexingService = new IndexingServiceImpl(serverDetails, HttpClientBuilder.create().build());
}

From source file:at.bitfire.davdroid.webdav.DavRedirectStrategyTest.java

@Override
protected void setUp() {
    httpClient = HttpClientBuilder.create().useSystemProperties().disableRedirectHandling().build();
}

From source file:org.wso2.security.tools.advisorytool.utils.Util.java

/**
 * This method is used to initiate an HTTP connection and retrieve the response.
 *
 * @param url//from w w  w.  ja  v  a 2 s.  c  o  m
 * @param
 * @return
 */
public static StringBuilder httpConnection(String url, List<Header> headerList) throws AdvisoryToolException {
    HttpResponse response = null;
    StringBuilder result = new StringBuilder();
    String line = "";

    try {
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);
        for (Header header : headerList) {
            request.addHeader(header.getHeaderName(), header.getHeaderValue());
        }
        response = client.execute(request);
    } catch (IOException e) {
        throw new AdvisoryToolException("Connection to the URL " + url + " failed", e);
    }

    try (BufferedReader rd = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent(), "UTF-8"))) {
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (IOException e) {
        throw new AdvisoryToolException("Error occured while reading the response from " + url, e);
    }
    return result;
}

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

public static HttpResponse sendRichiestaPagamento(String urlToInvoke, RichiestaPagamento richiestaPagamento,
        Logger log) throws Exception {
    HttpResponse responseGET = null;/*from  w ww  .  j a va  2 s .com*/
    try {
        log.debug("Invio 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();
        HttpPost richiestaPost = new HttpPost();

        richiestaPost.setURI(urlObj.toURI());

        log.debug("Serializzazione pagamento in corso...");
        byte[] bufferPagamento = JaxbUtils.toBytes(richiestaPagamento);
        log.debug("Serializzazione pagamento completata.");

        HttpEntity bodyEntity = new InputStreamEntity(new ByteArrayInputStream(bufferPagamento),
                ContentType.APPLICATION_XML);
        richiestaPost.setEntity(bodyEntity);
        richiestaPost.setHeader("Content-Type", ContentType.APPLICATION_XML.getMimeType());

        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;
    }
}

From source file:br.com.asisprojetos.request.GoogleChartRequest.java

public void makeRequest(String url, String fileName) {

    try {//from ww  w. j  ava2 s. co m

        FileOutputStream fos = null;

        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);

        logger.debug("Executando Request para Gerar Grafico no Servidor do Google Chart. URL : [{}]", url);

        request.addHeader("User-Agent", USER_AGENT);
        HttpResponse response = client.execute(request);

        logger.debug("Codigo de Resposta: {}", response.getStatusLine().getStatusCode());

        fos = new FileOutputStream(new File(String.format("%s/%s", config.getOutDirectory(), fileName)));

        HttpEntity httpEntity = response.getEntity();

        httpEntity.writeTo(fos);

        fos.close();

        logger.debug("Arquivo gerado no diretorio: {}/{} ", config.getOutDirectory(), fileName);

    } catch (Exception ex) {
        logger.error("Erro ao fazer Request para Servidor do Google Chart: {}", ex);
    }

}