Example usage for org.apache.http.client.methods CloseableHttpResponse close

List of usage examples for org.apache.http.client.methods CloseableHttpResponse close

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse close.

Prototype

public void close() throws IOException;

Source Link

Document

Closes this stream and releases any system resources associated with it.

Usage

From source file:com.continuuity.loom.provisioner.mock.MockWorker.java

private void finishTask(String taskId, ProvisionerAction action) throws IOException {
    LOG.debug("finishing task {}, which is a {} action.", taskId, action);
    try {/*w  ww.  j a v  a  2  s .  c  om*/
        JsonObject body = new JsonObject();
        body.addProperty("provisionerId", provisionerId);
        body.addProperty("workerId", provisionerId + "." + workerId);
        body.addProperty("taskId", taskId);
        body.addProperty("tenantId", tenantId);
        body.addProperty("status", "0");
        // include some random field in the result
        JsonObject result = new JsonObject();
        result.addProperty(RandomStringUtils.randomAlphanumeric(4), RandomStringUtils.randomAlphanumeric(8));
        if (action == ProvisionerAction.CONFIRM) {
            String ip = Joiner.on('.').join(RandomStringUtils.randomNumeric(3),
                    RandomStringUtils.randomNumeric(3), RandomStringUtils.randomNumeric(3),
                    RandomStringUtils.randomNumeric(3));
            result.addProperty("ipaddress", ip);
            LOG.debug("adding ip {}.", ip);
        }
        body.add("result", result);

        finishRequest.setEntity(new StringEntity(GSON.toJson(body)));
        CloseableHttpResponse response = httpClient.execute(finishRequest, httpContext);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode / 100 != 2) {
                LOG.error("Error finishing task {}. Got status code {} with message:\n{}", taskId, statusCode,
                        getResponseString(response));
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        LOG.error("Exception making finish request.", e);
    } finally {
        finishRequest.reset();
    }
}

From source file:com.msds.km.service.Impl.YunmaiAPIDrivingLicenseRecognitionServcieiImpl.java

@Override
protected DrivingLicense recognitionInternal(File file) throws RecognitionException {
    try {//from   w  w w .j  a  v a2 s  .c  om
        HttpPost httppost = new HttpPost(POST_URL);
        FileBody fileBody = new FileBody(file);

        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("img", fileBody)
                .addTextBody("action", "driving").addTextBody("callbackurl", "/idcard/").build();

        httppost.setEntity(reqEntity);

        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            String content = EntityUtils.toString(response.getEntity());
            EntityUtils.consume(response.getEntity());
            return this.parseDrivingLicense(content);
        } catch (IOException e) {
            throw new RecognitionException(
                    "can not post request to the url:" + POST_URL + ", please check the network.", e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                throw new RecognitionException(
                        "can not post request to the url:" + POST_URL + ", please check the network.", e);
            }
        }
    } catch (FileNotFoundException e) {
        throw new RecognitionException(
                "the file can not founded:" + file.getAbsolutePath() + ", please check the file.", e);
    } catch (ClientProtocolException e) {
        throw new RecognitionException(
                "can not post request to the url:" + POST_URL + ", please check the network.", e);
    } catch (IOException e) {
        throw new RecognitionException(
                "can not post request to the url:" + POST_URL + ", please check the network.", e);
    }
}

From source file:com.code42.demo.RestInvoker.java

/**
 * Builds and executes an HttpPost Request by appending the urlQuery parameter to the 
 * serverHost:serverPort variables and inserting the contents of the payload parameter.
 * Returns the data payload response as a JSONObject. 
 * //from ww  w . ja  v a2 s  .c  om
 * @param urlQuery
 * @param payload
 * @return org.json.simple.JSONObject
 * @throws Exception
 */
public JSONObject postAPI(String urlQuery, String payload) throws Exception {
    HttpClientBuilder hcs;
    CloseableHttpClient httpClient;
    hcs = HttpClients.custom().setDefaultCredentialsProvider(credsProvider);
    if (ssl) {
        hcs.setSSLSocketFactory(sslsf);
    }
    httpClient = hcs.build();
    JSONObject data;
    StringEntity payloadEntity = new StringEntity(payload, ContentType.APPLICATION_JSON);
    try {
        HttpPost httpPost = new HttpPost(ePoint + urlQuery);
        m_log.info("Executing request : " + httpPost.getRequestLine());
        m_log.debug("Payload : " + payload);
        httpPost.setEntity(payloadEntity);
        CloseableHttpResponse resp = httpClient.execute(httpPost);
        try {
            String jsonResponse = EntityUtils.toString(resp.getEntity());
            JSONParser jp = new JSONParser();
            JSONObject jObj = (JSONObject) jp.parse(jsonResponse);
            data = (JSONObject) jObj.get("data");
            m_log.debug(data);

        } finally {
            resp.close();
        }
    } finally {
        httpClient.close();
    }
    return data;
}

From source file:org.thoughtcrime.securesms.mms.MmsConnection.java

protected byte[] makeRequest(boolean useProxy) throws IOException {
    Log.w(TAG, "connecting to " + apn.getMmsc() + (useProxy ? " using proxy" : ""));

    HttpUriRequest request;//w w w.java 2  s. c om
    CloseableHttpClient client = null;
    CloseableHttpResponse response = null;
    try {
        request = constructRequest(useProxy);
        client = constructHttpClient();
        response = client.execute(request);

        Log.w(TAG, "* response code: " + response.getStatusLine());

        if (response.getStatusLine().getStatusCode() == 200) {
            return parseResponse(response.getEntity().getContent());
        }
    } finally {
        if (response != null)
            response.close();
        if (client != null)
            client.close();
    }

    throw new IOException("unhandled response code");
}

From source file:multichain.command.builders.QueryBuilderCommon.java

private Object executeRequest() throws IOException, ClientProtocolException, MultichainException {
    CloseableHttpResponse response = httpclient.execute(httppost);
    //      int statusCode = response.getStatusLine().getStatusCode();
    //      if (statusCode >= 400) {
    //         EntityUtils.consume(response.getEntity());
    //         throw new MultichainException("code :" + statusCode, "message : " + response.getStatusLine().getReasonPhrase());
    //      }/*from  ww w  .ja  va2s . c  om*/
    HttpEntity entity = response.getEntity();

    String rpcAnswer = EntityUtils.toString(entity);
    response.close();

    final Gson gson = new GsonBuilder().create();
    final MultiChainRPCAnswer multiChainRPCAnswer = gson.fromJson(rpcAnswer, MultiChainRPCAnswer.class);

    if (multiChainRPCAnswer != null && multiChainRPCAnswer.getError() == null) {
        return multiChainRPCAnswer.getResult();
    } else if (multiChainRPCAnswer != null && multiChainRPCAnswer.getError() != null) {
        throw new MultichainException("code :" + multiChainRPCAnswer.getError().get("code").toString(),
                "message : " + multiChainRPCAnswer.getError().get("message").toString());
    } else {
        throw new MultichainException(null, "General RPC Exceution Technical Error");
    }
}

From source file:de.bytefish.fcmjava.client.http.HttpClient.java

private <TRequestMessage> void internalPost(TRequestMessage requestMessage) throws Exception {

    CloseableHttpClient client = null;/*from  w ww.j a va2 s  .co  m*/
    try {
        client = httpClientBuilder.build();
        // Initialize a new post Request:
        HttpPost httpPost = new HttpPost(settings.getFcmUrl());

        // Set the JSON String as data:
        httpPost.setEntity(new StringEntity(JsonUtils.getAsJsonString(requestMessage), StandardCharsets.UTF_8));

        // Execute the Request:
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpPost);
            // Get the HttpEntity:
            HttpEntity entity = response.getEntity();

            // Let's be a good citizen and consume the HttpEntity:
            if (entity != null) {

                // Make Sure it is fully consumed:
                EntityUtils.consume(entity);
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:controlador.ControlEmpleados.java

/**
 * Solicita al server la SecretKey para cifrar/descifrar el resto de la comunicacin. Primero, hace una
 * peticin http de cuya respuesta abre un InputStream y almacena el stream de bytes en un fichero binario.
 * Este fichero es la clave pblica del servidor y se utilizar para descifrar asimtricamente la segunda
 * peticin, la cual contiene un objeto SecretKey que ser el utilizado para cifrar/descifrar de manera simtrica.
 *//*from   w w  w .j a v  a2s.  c  o  m*/
public void solicitarClave() {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpGet httpGet = new HttpGet(Configuration.getInstance().getServerUrl() + "/secretKey?opcion=public");
        CloseableHttpResponse response1 = httpclient.execute(httpGet,
                SessionContext.getInstance().getContext());
        try {
            HttpEntity entity1 = response1.getEntity();
            File f = new File("./server1024.publica");
            if (f.exists()) {
                f.delete();
            }
            IOUtils.copy(entity1.getContent(), new FileOutputStream(f));
        } finally {
            response1.close();
        }

        httpGet = new HttpGet(Configuration.getInstance().getServerUrl() + "/secretKey?opcion=secret");
        response1 = httpclient.execute(httpGet, SessionContext.getInstance().getContext());
        try {
            HttpEntity entity1 = response1.getEntity();
            String respuesta = EntityUtils.toString(entity1);
            byte[] clave = Base64.decodeBase64(respuesta);
            //descifro
            byte[] bufferPub = new byte[5000];
            File f = new File("server1024.publica");
            System.out.println(f.getAbsolutePath());
            FileInputStream in = new FileInputStream(f);
            int chars = in.read(bufferPub, 0, 5000);
            in.close();

            byte[] bufferPub2 = new byte[chars];
            System.arraycopy(bufferPub, 0, bufferPub2, 0, chars);

            Security.addProvider(new BouncyCastleProvider()); // Cargar el provider BC
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cifrador = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");

            KeyFactory keyFactoryRSA = KeyFactory.getInstance("RSA", "BC"); // Hace uso del provider BC
            // 4.2 Recuperar clave publica desde datos codificados en formato X509
            X509EncodedKeySpec clavePublicaSpec = new X509EncodedKeySpec(bufferPub2);
            PublicKey clavePublica2 = keyFactoryRSA.generatePublic(clavePublicaSpec);

            cifrador.init(Cipher.DECRYPT_MODE, clavePublica2); // Descrifra con la clave privada

            byte[] claveAES = cifrador.doFinal(clave);
            SecretKey originalKey = new SecretKeySpec(claveAES, 0, claveAES.length, "AES");
            SessionContext.getInstance().setSecretKey(originalKey);

        } finally {
            response1.close();
        }

    } catch (IOException ex) {
        Logger.getLogger(ControlEmpleados.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(ControlEmpleados.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            Logger.getLogger(ControlEmpleados.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.microsoft.applicationinsights.internal.channel.simplehttp.SimpleHttpChannel.java

@Override
public void send(Telemetry item) {
    try {/*from   w  w w  . j a  v a2s  . c om*/
        // Establish the payload.
        StringWriter writer = new StringWriter();
        //            item.serialize(new JsonWriter(writer));
        item.serialize(new JsonTelemetryDataSerializer(writer));

        // Send it.

        String payload = writer.toString();

        if (developerMode) {
            InternalLogger.INSTANCE.trace("SimpleHttpChannel, payload: %s", payload);
        }

        HttpPost request = new HttpPost(DEFAULT_SERVER_URI);
        StringEntity body = new StringEntity(payload, ContentType.create("application/x-json-stream"));
        request.setEntity(body);

        CloseableHttpClient httpClient = HttpClients.createDefault();

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(request);
            HttpEntity respEntity = response.getEntity();
            if (respEntity != null)
                respEntity.getContent().close();

            if (developerMode) {
                InternalLogger.INSTANCE.trace("SimpleHttpChannel, response: %s", response.getStatusLine());
            }
        } catch (IOException ioe) {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException ioeIn) {
            }
        }
    } catch (IOException ioe) {
    }
}

From source file:com.supermap.desktop.icloud.impl.LicenseServiceImpl.java

/**
 * @param response// w ww  .  jav a  2s.c  o  m
 * @return
 * @throws java.lang.UnsupportedOperationException
 * @throws IOException
 */
private String getJsonStrFromResponse(CloseableHttpResponse response)
        throws java.lang.UnsupportedOperationException, IOException {
    String result = "";
    try {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            System.out.println("----------------------");
            result = EntityUtils.toString(entity, "UTF-8");
            System.out.println(result);
            System.out.println("----------------------");
        }
    } finally {
        response.close();
    }

    return result;
}