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:br.mack.facade.ApiMarvelFacade.java

public Thumbnail obterUrlImagem(Integer idPersonagem) throws IOException {
    Thumbnail tn = null;/*w  w  w  .j  a v a  2 s.  c om*/
    long ts = Calendar.getInstance().getTimeInMillis();

    HttpClient cliente = HttpClients.createDefault();
    String stringToHash = ts + PRIVATE_KEY + PUBLIC_KEY;
    String hash = DigestUtils.md5Hex(stringToHash);

    String url = String.format("http://gateway.marvel.com:80/v1/public/characters/%d?ts=%d&apikey=%s&hash=%s",
            idPersonagem, ts, PUBLIC_KEY, hash);
    HttpGet httpget = new HttpGet(url);
    HttpResponse response = null;
    response = cliente.execute(httpget);
    System.out.println(response.getStatusLine());
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
        StringBuilder out = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            out.append(line);
        }
        String result = out.toString();
        Pattern p1 = Pattern.compile("\"thumbnail\":\\{[^{}]+\\}");
        Pattern p2 = Pattern.compile("\\{[^{}]+\\}");
        if (result.contains("thumbnail")) {
            Matcher matcher = p1.matcher(result);
            boolean find = matcher.find();
            if (find) {
                String g1 = matcher.group();
                matcher = p2.matcher(g1);
                find = matcher.find();
                if (find) {
                    ObjectMapper om = new ObjectMapper();
                    tn = om.readValue(matcher.group(), Thumbnail.class);
                }
            }
        }
        reader.close();
        instream.close();
    }

    return tn;

}

From source file:io.kamax.mxisd.backend.rest.RestProvider.java

public RestProvider(RestBackendConfig cfg) {
    this.cfg = cfg;

    client = HttpClients.createDefault();
    gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
    parser = new GsonParser(gson);
}

From source file:org.eclipse.emf.ecp.emf2web.json.JSONCrudOperator.java

public List<Map<String, Object>> readElements(String url, String type) throws IOException {
    final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

    final CloseableHttpClient httpClient = HttpClients.createDefault();
    try {//  w ww . j  ava2 s. c om
        final HttpGet httpGet = new HttpGet(url + "/" + type);

        final JSONResponseHandler<List<Map<String, Object>>> responseHandler = new JSONResponseHandler<List<Map<String, Object>>>();

        final List<Map<String, Object>> resultList = responseHandler
                .handleResponse(httpClient.execute(httpGet));

        for (final Map<String, Object> object : resultList) {
            if (object == null) {
                continue;
            }

            result.add(object);
        }
    } finally {
        httpClient.close();
    }

    return result;
}

From source file:com.fpmislata.banco.business.service.impl.PeticionRetirarDineroServiceImpl.java

@Override
public void sendPeticionBancaria(CredencialesBancarias credencialesBancarias, String cccOrigen, String concepto,
        BigDecimal importe, String codigoEntidadBancaria) throws BusinessException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {/*from w ww  . j a  v a  2  s .c o m*/
        Extraccion extraccion = new Extraccion();

        extraccion.setCodigoCuentaCliente(cccOrigen);
        extraccion.setCodigoEntidadBancaria(codigoEntidadBancaria);
        extraccion.setConcepto(concepto);
        extraccion.setImporte(importe);
        extraccion.setPin(credencialesBancarias.getPin());

        HttpPost httpPost = new HttpPost(credencialesBancarias.getUrl() + "/retirar");
        StringEntity stringEntity = new StringEntity(jsonTransformer.toJson(extraccion));
        httpPost.setEntity(stringEntity);
        httpPost.setHeader("Content-type", "application/json");
        httpClient.execute(httpPost);
    } catch (IOException ex) {
        Logger.getLogger(BancoCentralServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        throw new BusinessException("Error por cuestiones ajenas", "BancoCentral");
    } finally {
        try {
            httpClient.close();
        } catch (IOException ex) {
            Logger.getLogger(BancoCentralServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.restfiddle.handler.http.GetHandler.java

public RfResponseDTO process(RfRequestDTO rfRequestDTO) throws IOException {
    RfResponseDTO response = null;//ww  w  .  jav a2 s  .  co  m
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(rfRequestDTO.getApiUrl());
    try {
        response = processHttpRequest(httpGet, httpclient);

    } finally {
        httpclient.close();
    }
    return response;
}

From source file:cn.aofeng.demo.httpclient.HttpClientBasic.java

public void get() throws URISyntaxException, ClientProtocolException, IOException {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet get = new HttpGet(_targetHost + "/get");
    CloseableHttpResponse response = client.execute(get);
    processResponse(response);/*w w  w  . jav  a 2  s.  c  o m*/
}

From source file:httpServerClient.app.QuickStart.java

public static void sendMessage(String[] args) throws Exception {
    // arguments to run Quick start POST:
    // args[0] POST
    // args[1] IPAddress of server
    // args[2] port No.
    // args[3] user name
    // args[4] myMessage
    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {/*from   ww w  .  ja va  2s .com*/
        HttpPost httpPost = new HttpPost("http://" + args[1] + ":" + args[2] + "/sendMessage");
        // httpPost.setEntity(new StringEntity("lubo je kral"));
        httpPost.setEntity(
                new StringEntity("{\"name\":\"" + args[3] + "\",\"myMessage\":\"" + args[4] + "\"}"));
        CloseableHttpResponse response1 = httpclient.execute(httpPost);
        // The underlying HTTP connection is still held by the response
        // object
        // to allow the response content to be streamed directly from the
        // network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally
        // clause.
        // Please note that if response content is not fully consumed the
        // underlying
        // connection cannot be safely re-used and will be shut down and
        // discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();

            /*
             * Vypisanie odpovede do konzoly a discard dat zo serveru.
             */

            System.out.println(EntityUtils.toString(entity1));
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

    } finally {
        httpclient.close();
    }
}

From source file:com.esri.geoevent.test.performance.streamservice.StreamMetadata.java

public StreamMetadata(String url) {
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode schema = mapper.readTree(entity.getContent());
        JsonNode streamUrls = schema.get("streamUrls");
        // JsonNode fields = schema.get("fields");

        //parse out the stream service urls
        for (JsonNode protocol : streamUrls) {
            if (protocol.get("transport").asText().equals("ws")) {
                for (JsonNode urlNode : protocol.get("urls")) {
                    wsUrls.add(urlNode.asText());
                }//from   w w w  .ja v  a 2s . c  om
            }
        }
    } catch (Exception error) {
        error.printStackTrace();
    }
}

From source file:HttpClient.HttpCalendarClient.java

public HttpCalendarClient() {
    httpclient = HttpClients.createDefault();
}

From source file:com.econcept.pingconnectionutility.utility.PingConnectionUtility.java

private static void httpPingable(String targetURI) throws IOException, URISyntaxException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet();
    httpGet.setURI(new URI(targetURI));
    CloseableHttpResponse response = httpClient.execute(httpGet);

    int currentCode = response.getStatusLine().getStatusCode();
    try {//from   w  w  w .  j  av a 2  s  .co  m

        if (currentCode >= 200 && currentCode < 300) {
            HttpEntity entity = response.getEntity();

            InputStream responseStream = entity.getContent();

            StringWriter writer = new StringWriter();

            IOUtils.copy(responseStream, writer, "UTF-8");

            System.out.println("Target Server are ok: " + currentCode);
            System.out.println(writer.toString());

            EntityUtils.consume(entity);
        } // if
        else {
            System.out.println("Target Server are not ok: " + currentCode);
        } // else
    } // try
    finally {
        response.close();
    } // finally

}