Example usage for org.apache.http.impl.client HttpClients createDefault

List of usage examples for org.apache.http.impl.client HttpClients createDefault

Introduction

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

Prototype

public static CloseableHttpClient createDefault() 

Source Link

Document

Creates CloseableHttpClient instance with default configuration.

Usage

From source file:bit.changepurse.wdk.http.HTTPClient.java

public HTTPClient(ActionRegistry aRegistry) {
    client = HttpClients.createDefault();
    registry = aRegistry;
}

From source file:io.wcm.devops.maven.nodejsproxy.resource.TestContext.java

static CloseableHttpClient getHttpClient() {
    return HttpClients.createDefault();
}

From source file:aop.controller.RequestController.java

public void sendPostReq(int id, String type) throws Exception {

    boolean debug = false;
    String url = "http://localhost:1337/";

    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {//from w  ww.  j  a v  a  2 s  .  c om
        HttpPost post = new HttpPost(url);

        // add header
        post.setHeader("User-Agent", USER_AGENT);

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("id", Integer.toString(id)));
        urlParameters.add(new BasicNameValuePair("type", type));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        HttpResponse response = httpClient.execute(post);
        if (debug) {
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + post.getEntity());
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

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

            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }

            System.out.println(result.toString());
        }
    } finally {
        httpClient.close();
    }
}

From source file:com.kingmed.dp.ndp.NDPConnectionManager.java

@Override
public void connect() throws Exception {
    String signinUrl = ndpServe.getUrlSignin();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from  w  ww .  j  a  v  a  2s .  c  om*/
        HttpGet httpget = new HttpGet(signinUrl);
        String responseBody = httpclient.execute(httpget, new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse hr) throws ClientProtocolException, IOException {
                int status = hr.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = hr.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

        });
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        httpclient.close();
    }
}

From source file:webrequester.CouchDBWebRequest.java

public String requestWithPut(String content) {
    String s = "";
    try {/*  w  ww .j  a  va  2 s  . c o m*/

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPut httpput = new HttpPut(buildURI().toString());

        StringEntity se = new StringEntity(content);
        httpput.setEntity(se);

        CloseableHttpResponse response = httpclient.execute(httpput);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                s = EntityUtils.toString(entity, "UTF-8");
            }
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        return null;
    }
    return s;
}

From source file:org.duracloud.duradmin.integration.selenium.HomeTest.java

public void testForFavicon() throws Exception {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet get = new HttpGet(getBaseURL() + "favicon.ico");
    HttpResponse response = client.execute(get);
    assertEquals(200, response.getStatusLine().getStatusCode());
    assertTrue(response.getHeaders("Content-Type").length == 0);
}

From source file:ch.asadzia.cognitive.EmotionDetect.java

public ServiceResult process() {

    HttpClient httpclient = HttpClients.createDefault();

    try {/*  w  w w.ja  v a 2 s  .  c  om*/
        URIBuilder builder = new URIBuilder("https://api.projectoxford.ai/emotion/v1.0/recognize");

        URI uri = builder.build();
        HttpPost request = new HttpPost(uri);
        request.setHeader("Content-Type", "application/octet-stream");
        request.setHeader("Ocp-Apim-Subscription-Key", apikey);

        // Request body
        FileEntity reqEntity = new FileEntity(imageData);
        request.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            String responseStr = EntityUtils.toString(entity);

            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                System.err.println(responseStr);
                return null;
            }

            JSONArray jsonArray = (JSONArray) new JSONParser().parse(responseStr);
            JSONObject jsonObject = (JSONObject) jsonArray.get(0);

            HashMap<char[], Double> scores = (HashMap) jsonObject.get("scores");

            Map.Entry<char[], Double> maxEntry = null;

            for (Map.Entry<char[], Double> entry : scores.entrySet()) {
                System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

                if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) {
                    maxEntry = entry;
                }
            }
            Object key = maxEntry.getKey();

            String winningEmotionName = (String) key;

            ServiceResult result = new ServiceResult(translateEmotion(winningEmotionName), winningEmotionName);

            System.out.println(responseStr);

            return result;
        }
    } catch (Exception e) {
        System.err.println(e.toString());
    }
    return null;
}

From source file:com.continuuity.loom.TestHelper.java

public static SchedulableTask takeTask(String loomUrl, TakeTaskRequest request) throws Exception {
    HttpPost httpPost = new HttpPost(String.format("%s/v1/loom/tasks/take", loomUrl));
    httpPost.setEntity(new StringEntity(GSON.toJson(request)));

    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = httpClient.execute(httpPost);
    try {//from   w w w .  j  av  a2s . c  o  m
        Assert.assertEquals(2, response.getStatusLine().getStatusCode() / 100);
        if (response.getEntity() == null) {
            return null;
        }
        return GSON.fromJson(EntityUtils.toString(response.getEntity()), SchedulableTask.class);
    } finally {
        response.close();
    }
}

From source file:model.WebServiceRequest.java

public String getResponse(String pais, String ciudad) {
    pais = pais.replace(" ", "%20");
    ciudad = ciudad.replace(" ", "%20");
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpGet httpGet = new HttpGet("http://www.webservicex.net/globalweather.asmx/GetWeather?CityName="
                + ciudad + "&CountryName=" + pais);
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

        System.out.println("GET Response Status: " + httpResponse.getStatusLine().getStatusCode());

        StringBuilder response;//from   w w  w . j av  a  2 s  . co m
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent()))) {
            String inputLine;
            response = new StringBuilder();
            while ((inputLine = reader.readLine()) != null) {
                response.append(inputLine);
            }
        }
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            return response.toString();
        } else {
            return "Error.";
        }

    } catch (IOException ex) {
        Logger.getLogger(WebServiceRequest.class.getName()).log(Level.SEVERE, null, ex);
    }
    JOptionPane.showMessageDialog(null, "Se ha presentado un error al acceder al servicio web.");
    return null;
}

From source file:io.uploader.drive.drive.largefile.HttpClientUtils.java

public static CloseableHttpClient getHttpClient(HasProxySettings proxySetting) {
    // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e475

    CloseableHttpClient httpclient = null;
    if (proxySetting != null && proxySetting.isActive()) {
        logger.info("Set the http proxy (" + proxySetting.getHost() + ":" + proxySetting.getPort() + ")");
        CredentialsProvider credsProvider = Preconditions.checkNotNull(proxySetting.getCredentialsProvider());
        HttpHost proxy = new HttpHost(proxySetting.getHost(), proxySetting.getPort());
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        httpclient = HttpClients.custom().setRoutePlanner(routePlanner)
                .setDefaultCredentialsProvider(credsProvider).build();
    } else {/* w w w.  j  a  v a2 s . c om*/
        httpclient = HttpClients.createDefault();
    }
    return httpclient;
}