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.matmaul.freeboxos.internal.RestManager.java

public RestManager(FreeboxOsClient client, String host) {
    this.client = client;
    this.baseAddress = "http://" + host + "/api/v3/";
    httpClient = HttpClientBuilder.create().build();
    jsonMapper = new ObjectMapper();
    jsonMapper.enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
    jsonMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    jsonMapper.getDeserializationConfig().addHandler(new DeserializationProblemHandler() {

        @Override//from   w  w w.j a  v a2s.co  m
        public boolean handleUnknownProperty(DeserializationContext ctxt, JsonDeserializer<?> deserializer,
                Object beanOrClass, String propertyName) throws IOException, JsonProcessingException {
            if ("challenge".equals(propertyName) || "password_salt".equals(propertyName)) {
                return true;
            }
            return false;
        }
    });
}

From source file:org.openstreetmap.josm.plugins.mapillary.actions.MapillarySubmitCurrentChangesetAction.java

@Override
public void actionPerformed(ActionEvent event) {
    String token = Main.pref.get("mapillary.access-token");
    if (token == null || token.trim().isEmpty()) {
        PluginState.notLoggedInToMapillaryDialog();
        return;/*from  ww w.  j a v a 2s  .c  om*/
    }
    PluginState.setSubmittingChangeset(true);
    MapillaryUtils.updateHelpText();
    HttpClientBuilder builder = HttpClientBuilder.create();
    HttpPost httpPost = new HttpPost(MapillaryURL.submitChangesetURL().toString());
    httpPost.addHeader("content-type", "application/json");
    httpPost.addHeader("Authorization", "Bearer " + token);
    JsonArrayBuilder changes = Json.createArrayBuilder();
    MapillaryLocationChangeset locationChangeset = MapillaryLayer.getInstance().getLocationChangeset();
    for (MapillaryImage image : locationChangeset) {
        changes.add(Json.createObjectBuilder().add("image_key", image.getKey()).add("values",
                Json.createObjectBuilder()
                        .add("from", Json.createObjectBuilder().add("ca", image.getCa())
                                .add("lat", image.getLatLon().getY()).add("lon", image.getLatLon().getX()))
                        .add("to",
                                Json.createObjectBuilder().add("ca", image.getTempCa())
                                        .add("lat", image.getTempLatLon().getY())
                                        .add("lon", image.getTempLatLon().getX()))));
    }
    String json = Json.createObjectBuilder().add("change_type", "location").add("changes", changes)
            .add("request_comment", "JOSM-created").build().toString();
    try (CloseableHttpClient httpClient = builder.build()) {
        httpPost.setEntity(new StringEntity(json));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            String key = Json.createReader(response.getEntity().getContent()).readObject().getString("key");
            synchronized (MapillaryUtils.class) {
                Main.map.statusLine.setHelpText(
                        String.format("%s images submitted, Changeset key: %s", locationChangeset.size(), key));
            }
            locationChangeset.cleanChangeset();

        }

    } catch (IOException e) {
        logger.error("got exception", e);
        synchronized (MapillaryUtils.class) {
            Main.map.statusLine.setHelpText("Error submitting Mapillary changeset: " + e.getMessage());
        }
    } finally {
        PluginState.setSubmittingChangeset(false);
    }
}

From source file:org.eclipse.rcptt.internal.testrail.APIClient.java

private String sendRequest(HttpUriRequest request) {
    HttpClient client = HttpClientBuilder.create().build();
    setUpHeaders(request);/*w  w w . j a  v a  2s.  c om*/
    try {
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();
        String entity = EntityUtils.toString(response.getEntity());
        if (status.getStatusCode() != HttpStatus.SC_OK) {
            TestRailPlugin.log(MessageFormat.format(Messages.APIClient_HTTPError, status.getStatusCode(),
                    entity.equals("") ? status.getReasonPhrase() : entity));
            return null;
        }
        TestRailPlugin.logInfo(MessageFormat.format(Messages.APIClient_RecievedResponse, entity));
        return entity;
    } catch (Exception e) {
        TestRailPlugin.log(Messages.APIClient_ErrorWhileSendingRequest, e);
        return null;
    }
}

From source file:tds.itemscoringengine.web.server.ItemScoringEngineHttpWebHelper.java

public ItemScoringEngineHttpWebHelper() {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    _client = HttpClientBuilder.create().setConnectionManager(connectionManager).build();
}

From source file:at.ac.tuwien.dsg.cloudlyra.utils.RestHttpClient.java

public void callPostMethod(List<NameValuePair> paramList) {

    try {/*ww w. j av  a  2s.  com*/

        HttpPost post = new HttpPost(url);

        // add header
        post.setHeader("Host", "smartsoc.infosys.tuwien.ac.at");
        //post.setHeader("User-Agent", USER_AGENT);
        //post.setHeader("Connection", "keep-alive");
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");

        // set content
        post.setEntity(new UrlEncodedFormEntity(paramList));

        logger.log(Level.INFO, "\nSending 'POST' request to URL : " + url);
        logger.log(Level.INFO, "Post parameters : " + paramList);
        System.out.println();

        HttpClient client = HttpClientBuilder.create().build();
        HttpResponse response = client.execute(post);

        int responseCode = response.getStatusLine().getStatusCode();

        logger.log(Level.INFO, "Response Code : " + responseCode);

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

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

        logger.log(Level.INFO, result.toString());

    } catch (Exception ex) {

    }

}

From source file:org.apache.solr.client.solrj.impl.ExternalHttpClientTest.java

/**
 * The internal client created by HttpSolrClient is a SystemDefaultHttpClient
 * which takes care of merging request level params (such as timeout) with the
 * configured defaults.//w w w  .j  a v a  2 s  .c o m
 *
 * However, if an external HttpClient is passed to HttpSolrClient,
 * the logic in InternalHttpClient.executeMethod replaces the configured defaults
 * by request level params if they exist. That is why we must test a setting such
 * as timeout with an external client to assert that the defaults are indeed being
 * used
 *
 * See SOLR-6245 for more details
 */
@Test
public void testTimeoutWithExternalClient() throws Exception {

    HttpClientBuilder builder = HttpClientBuilder.create();
    RequestConfig config = RequestConfig.custom().setSocketTimeout(2000).build();
    builder.setDefaultRequestConfig(config);

    try (CloseableHttpClient httpClient = builder.build();
            HttpSolrClient solrClient = new HttpSolrClient(jetty.getBaseUrl().toString() + "/slow/foo",
                    httpClient)) {

        SolrQuery q = new SolrQuery("*:*");
        try {
            solrClient.query(q, SolrRequest.METHOD.GET);
            fail("No exception thrown.");
        } catch (SolrServerException e) {
            assertTrue(e.getMessage().contains("Timeout"));
        }
    }
}

From source file:io.github.hebra.elasticsearch.beat.meterbeat.device.dlink.DSPW215.java

@Override
public String fetchData() {
    final String url = config.getBaseurl().concat("/my_cgi.cgi?")
            .concat(new BigInteger(130, secureRandom).toString(32));

    try {//from   ww  w.j a v  a2  s. co m
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();

        HttpClient client = HttpClientBuilder.create().setConnectionTimeToLive(5, TimeUnit.SECONDS)
                .setConnectionReuseStrategy(new NoConnectionReuseStrategy()).build();
        HttpPost post = new HttpPost(url);

        post.setConfig(requestConfig);

        post.setHeader("User-Agent", USER_AGENT);
        post.setHeader("Accept-Language", "en-US,en;q=0.5");

        final List<NameValuePair> urlParameters = new ArrayList<>();
        urlParameters.add(new BasicNameValuePair("request", "create_chklst"));
        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        final HttpResponse response = client.execute(post);

        final String content = IOUtils.toString(response.getEntity().getContent(), Charsets.US_ASCII);

        EntityUtils.consume(response.getEntity());

        return content.split("Meter Watt: ", 2)[1].trim();
    } catch (IOException ioEx) {
        log.error("Timeout when trying to read from {} on {}: {}", config.getName(), config.getBaseurl(),
                ioEx.getMessage());
    }

    return null;
}

From source file:graphene.augment.mitie.dao.MITIERestAPIConnectionImpl.java

@Override
public String performQuery(final String inputText)
        throws DataAccessException, ClientProtocolException, IOException {
    final HttpClient client = HttpClientBuilder.create().build();

    final HttpPost post = new HttpPost(url);
    post.setHeader("Authorization", "Basic " + HttpUtil.getAuthorizationEncoding(basicAuth));
    final JSONObject obj = new JSONObject();
    obj.put("text", inputText);

    final StringEntity entity = new StringEntity(obj.toString());
    post.setEntity(entity);//from w w  w .j  av  a  2s  . c o  m
    final HttpResponse response = client.execute(post);

    final BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    final StringBuffer sb = new StringBuffer();
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    return sb.toString();
}

From source file:com.wirelust.sonar.plugins.bitbucket.client.CustomApacheHttpClient4EngineTest.java

@Before
public void init() throws Exception {
    httpClient = HttpClientBuilder.create().build();

    engine = new CustomApacheHttpClient4Engine(httpClient);

    clientBuilder = new CustomResteasyClientBuilder();
    client = clientBuilder.build();//w  ww  .ja  va 2  s . com
    client.register(JacksonConfigurationProvider.class);

    ResteasyProviderFactory resteasyProviderFactory = new ResteasyProviderFactory();
    clientConfiguration = new ClientConfiguration(resteasyProviderFactory);
    headers = new ClientRequestHeaders(clientConfiguration);

    uri = new URI("http://127.0.0.1");

    //request = new ClientInvocation(client, uri, headers, clientConfiguration);
    request = mock(ClientInvocation.class);
    when(request.getHeaders()).thenReturn(headers);
    when(request.getClientConfiguration()).thenReturn(clientConfiguration);
}

From source file:gui.EventAllReader.java

@Override
public void run() {

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 1000).build();
    HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
    //HttpClient client = new DefaultHttpClient();

    HttpGet request = new HttpGet("https://api.guildwars2.com/v1/event_names.json?lang=" + this.language);

    HttpResponse response;/*  ww w  .ja  v a  2 s .c  o  m*/

    String line = "";
    String out = "";

    while (!this.isInterrupted()) {

        try {

            response = client.execute(request);

            if (response.getStatusLine().toString().contains("200")) {

                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")));

                line = "";
                out = "";

                while ((line = rd.readLine()) != null) {

                    out = out + line;
                }

                JSONParser parser = new JSONParser();

                Object obj;

                this.result.clear();

                try {

                    obj = parser.parse(out);

                    JSONArray array = (JSONArray) obj;

                    for (int i = 0; i < array.size(); i++) {

                        JSONObject obj2 = (JSONObject) array.get(i);

                        if (obj2.get("name") != null) {

                            this.result.put(obj2.get("id"), obj2.get("name"));
                        }
                    }

                    this.apimanager.updateToolTips();

                    request.releaseConnection();
                    this.interrupt();
                } catch (ParseException ex) {
                    try {
                        Logger.getLogger(ApiManager.class.getName()).log(Level.SEVERE, null, ex);

                        request.releaseConnection();
                        Thread.sleep(5000);
                    } catch (InterruptedException ex1) {
                        Logger.getLogger(EventAllReader.class.getName()).log(Level.SEVERE, null, ex1);
                    }
                }
            } else {
                try {
                    request.releaseConnection();
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(EventAllReader.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } catch (IOException | IllegalStateException ex) {
            try {
                Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex);

                request.releaseConnection();
                Thread.sleep(5000);
            } catch (InterruptedException ex1) {
                Logger.getLogger(EventAllReader.class.getName()).log(Level.SEVERE, null, ex1);

                this.interrupt();
            }
        }
    }
}