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

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

Introduction

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

Prototype

HttpEntity getEntity();

Source Link

Usage

From source file:webrequester.CouchDBWebRequest.java

public String requestWithPut(String content) {
    String s = "";
    try {/*from  w  w  w . j av a  2 s.c  om*/

        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:com.nibss.util.Request.java

public void get(String url) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/* w ww.ja va2 s  .  c o m*/
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        try {
            HttpEntity entity1 = response1.getEntity();

            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:ar.edu.ubp.das.src.chat.actions.LogoutAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        HttpPost httpPost = new HttpPost("http://25.136.78.82:8080/logout/");
        httpPost.addHeader("Authorization", "BEARER " + authToken);
        httpPost.addHeader("accept", "application/json");

        CloseableHttpResponse postResponse = httpClient.execute(httpPost);

        HttpEntity responseEntity = postResponse.getEntity();
        StatusLine responseStatus = postResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }//ww  w  . ja  va  2s.c om

        request.getSession().removeAttribute("token");

        return mapping.getForwardByName("success");

    } catch (IOException | RuntimeException e) {
        request.setAttribute("message", "Error al realizar logout: " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("failure");
    }
}

From source file:org.wuspba.ctams.ws.ITPersonController.java

protected static void delete() throws Exception {
    List<String> ids = new ArrayList<>();

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpGet httpGet = new HttpGet(uri);

    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING);

        HttpEntity entity = response.getEntity();

        CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity);

        for (Person p : doc.getPeople()) {
            ids.add(p.getId());//ww w  .j a v  a 2 s.  c  o  m
        }

        EntityUtils.consume(entity);
    }

    for (String id : ids) {
        httpclient = HttpClients.createDefault();

        uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
                .setParameter("id", id).build();

        HttpDelete httpDelete = new HttpDelete(uri);

        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpDelete);

            assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

            HttpEntity responseEntity = response.getEntity();

            EntityUtils.consume(responseEntity);
        } catch (UnsupportedEncodingException ex) {
            LOG.error("Unsupported coding", ex);
        } catch (IOException ioex) {
            LOG.error("IOException", ioex);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ex) {
                    LOG.error("Could not close response", ex);
                }
            }
        }
    }
}

From source file:utils.APIImporter.java

/**
 * Publishing each imported APIs/*  ww  w  . ja  va  2 s  .c o  m*/
 * @param apiFolder path to the imported folder
 * @param token access token
 * @throws APIImportException
 */
private static void publishAPI(String apiFolder, String token) throws APIImportException {
    String apiId = null;
    try {
        //getting api.json of imported API
        String pathToJSONFile = apiFolder + ImportExportConstants.JSON_FILE_LOCATION;
        String jsonContent = FileUtils.readFileToString(new File(pathToJSONFile));
        //building API id
        apiId = ImportExportUtils.readJsonValues(jsonContent, ImportExportConstants.API_PROVIDER) + "-"
                + ImportExportUtils.readJsonValues(jsonContent, ImportExportConstants.API_NAME) + "-"
                + ImportExportUtils.readJsonValues(jsonContent, ImportExportConstants.API_VERSION);

        String url = config.getPublisherUrl() + "apis";
        CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
        HttpPost request = new HttpPost(url);
        request.setEntity(new StringEntity(jsonContent, ImportExportConstants.CHARSET));
        request.setHeader(HttpHeaders.AUTHORIZATION, ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + token);
        request.setHeader(HttpHeaders.CONTENT_TYPE, ImportExportConstants.CONTENT_JSON);
        CloseableHttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == Response.Status.CONFLICT.getStatusCode()) {
            if (config.getUpdateApi()) {
                updateApi(jsonContent, apiId, token, apiFolder);
            } else {
                errorMsg = "API " + apiId + " already exists. ";
                System.out.println(errorMsg);
            }
        } else if (response.getStatusLine().getStatusCode() == Response.Status.CREATED.getStatusCode()) {
            System.out.println("creating API " + apiId);
            //getting created API's uuid
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString(entity, ImportExportConstants.CHARSET);
            String uuid = ImportExportUtils.readJsonValues(responseString, ImportExportConstants.UUID);
            if (StringUtils.isNotBlank(
                    ImportExportUtils.readJsonValues(jsonContent, ImportExportConstants.THUMBNAIL))) {
                addAPIImage(apiFolder, token, uuid);
            }
            //Adding API documentations
            addAPIDocuments(apiFolder, token, uuid);

            //addAPISequences(pathToArchive, importedApi);
            // addAPISpecificSequences(pathToArchive, importedApi);
            // addAPIWsdl(pathToArchive, importedApi);
            System.out.println("Importing API " + apiId + " was successful");

        } else {
            errorMsg = response.getStatusLine().toString();
            log.error(errorMsg);
            throw new APIImportException(errorMsg);
        }
    } catch (IOException e) {
        String errorMsg = "cannot find details of " + apiId + " for import";
        log.error(errorMsg, e);
        throw new APIImportException(errorMsg, e);
    }
}

From source file:Onlinedata.MainSendRequest.java

public void uploadData(String filename, String toBeUploaded) {
    upload = filename + ";" + toBeUploaded;
    uploadurl = baseurl;// www  .  j  av a 2 s  .  c om
    try {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        StringEntity cliententity = new StringEntity(upload, ContentType.create("plain/text", Consts.UTF_8));
        HttpPost httppost = new HttpPost(uploadurl);
        httppost.setEntity(cliententity);
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            HttpEntity serverentity = response.getEntity();
            if (serverentity != null) {
                long len = serverentity.getContentLength();
                if (len != -1 && len < 2048) {
                    System.out.println(EntityUtils.toString(serverentity));
                } else {
                    // Stream content out
                }
            }
        } catch (IOException | ParseException ex) {
            Logger.getLogger(MainSendRequest.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            response.close();
        }
        httpclient.close();
    } catch (IOException ex) {
        Logger.getLogger(MainSendRequest.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * Log the error that occurred and provide an exception that encapsulates the failure as best as
 * possible. This means parsing the output and if its from RTC extract the stack trace from 
 * there./*  w  ww.j  a v  a2s . c  o  m*/
 * @param fullURI The URI requested
 * @param httpResponse The response from the request
 * @param message A message for the failure if nothing can be detected from the response
 * @return An exception representing the failure
 */
@SuppressWarnings("rawtypes")
private static IOException logError(String fullURI, CloseableHttpResponse httpResponse, String message) {
    printMessageHeaders(httpResponse);

    IOException error = new IOException(message);
    try {
        InputStreamReader inputStream = new InputStreamReader(httpResponse.getEntity().getContent(), UTF_8);
        try {
            String response = IOUtils.toString(inputStream);
            // this is one lonnnng string if its a stack trace.
            // try to get it as JSON so we can output it in a more friendly way.
            try {
                JSON json = JSONSerializer.toJSON(response);
                response = json.toString(4);
                if (json instanceof JSONObject) {
                    // see if we have a stack trace
                    JSONObject jsonObject = (JSONObject) json;
                    String errorMessage = jsonObject.getString("errorMessage"); //$NON-NLS-1$
                    error = new IOException(errorMessage);
                    JSONArray trace = jsonObject.getJSONArray("errorTraceMarshall"); //$NON-NLS-1$
                    List<StackTraceElement> stackElements = new ArrayList<StackTraceElement>(trace.size());
                    for (Iterator iterator = trace.iterator(); iterator.hasNext();) {
                        Object element = iterator.next();
                        if (element instanceof JSONObject) {
                            JSONObject jsonElement = (JSONObject) element;
                            String cls = jsonElement.getString("errorTraceClassName"); //$NON-NLS-1$
                            String method = jsonElement.getString("errorTraceMethodName"); //$NON-NLS-1$
                            String file = jsonElement.getString("errorTraceFileName"); //$NON-NLS-1$
                            int line = jsonElement.getInt("errorTraceLineNumber"); //$NON-NLS-1$
                            StackTraceElement stackElement = new StackTraceElement(cls, method, file, line);
                            stackElements.add(stackElement);
                        }
                    }
                    error.setStackTrace(stackElements.toArray(new StackTraceElement[stackElements.size()]));

                    // our RTC responses have the stack trace in there twice. Remove 1 copy of it.
                    jsonObject.remove("errorTraceMarshall"); //$NON-NLS-1$
                    response = jsonObject.toString(4);
                }
            } catch (JSONException e) {
                // not JSON or not a RTC stack trace in the JSONObject so just log what we have
            }
            LOGGER.finer(response);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                LOGGER.finer("Failed to close the result input stream for request: " + fullURI); //$NON-NLS-1$
            }
        }
    } catch (IOException e) {
        LOGGER.finer("Unable to capture details of the failure"); //$NON-NLS-1$
    }
    return error;
}

From source file:goofyhts.torrentkinesis.test.HttpTest.java

@Test
public void testGet() {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpClientContext context = new HttpClientContext();
        CredentialsProvider credProv = new BasicCredentialsProvider();
        credProv.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("root", "Whcinhry21#"));
        context.setCredentialsProvider(credProv);
        HttpGet httpGet = new HttpGet("http://localhost:8150/gui/token.html");

        CloseableHttpResponse response = client.execute(httpGet, context);
        String responseBody = IOUtils.toString(response.getEntity().getContent());
        System.out.println(responseBody);
        Document doc = Jsoup.parse(responseBody);
        System.out.println(doc.getElementById("token").text());
    } catch (ClientProtocolException e) {
        e.printStackTrace();/*from  w w  w.j a  v  a  2  s.  com*/
    } catch (IOException e) {
        e.printStackTrace();
    }
    //Assert.assertTrue(true);
}

From source file:org.commonjava.indy.ftest.core.urls.StoreOneAndSourceStoreUrlInHtmlListingTest.java

@Test
public void storeOneFileAndVerifyItInParentDirectoryListing() throws Exception {
    final byte[] data = "this is a test".getBytes();
    final ByteArrayInputStream stream = new ByteArrayInputStream(data);
    final String root = "/path/to/";
    final String path = root + "foo.txt";

    client.content().store(hosted, STORE, path, stream);

    final IndyClientHttp http = getHttp();

    final HttpGet request = http.newRawGet(client.content().contentUrl(hosted, STORE, root));

    request.addHeader("Accept", "text/html");

    final CloseableHttpClient hc = http.newClient();
    final CloseableHttpResponse response = hc.execute(request);

    final InputStream listing = response.getEntity().getContent();
    final String html = IOUtils.toString(listing);

    // TODO: Charset!!
    final Document doc = Jsoup.parse(html);
    for (final Element item : doc.select("a.source-link")) {
        final String fname = item.text();
        System.out.printf("Listing contains: '%s'\n", fname);
        final String href = item.attr("href");
        final String expected = client.content().contentUrl(hosted, STORE);

        assertThat(fname + " does not have a href", href, notNullValue());
        assertThat(fname + " has incorrect link: '" + href + "' (" + href.getClass().getName()
                + ")\nshould be: '" + expected + "' (String)", href, equalTo(expected));
    }//from  ww  w . ja  va2 s  .  c o m
}

From source file:org.commonjava.indy.ftest.core.urls.StoreOneAndVerifyInHtmlListingTest.java

@Test
public void storeOneFileAndVerifyItInParentDirectoryListing() throws Exception {
    final byte[] data = "this is a test".getBytes();
    final ByteArrayInputStream stream = new ByteArrayInputStream(data);
    final String root = "/path/to/";
    final String path = root + "foo.txt";

    client.content().store(hosted, STORE, path, stream);

    final IndyClientHttp http = getHttp();

    final HttpGet request = http.newRawGet(client.content().contentUrl(hosted, STORE, root));

    request.addHeader("Accept", "text/html");

    final CloseableHttpClient hc = http.newClient();
    final CloseableHttpResponse response = hc.execute(request);

    final InputStream listing = response.getEntity().getContent();
    final String html = IOUtils.toString(listing);

    // TODO: Charset!!
    final Document doc = Jsoup.parse(html);
    for (final Element item : doc.select("a.item-link")) {
        final String fname = item.text();
        System.out.printf("Listing contains: '%s'\n", fname);
        final String href = item.attr("href");
        final String expected = client.content().contentUrl(hosted, STORE, root, fname);

        assertThat(fname + " does not have a href", href, notNullValue());
        assertThat(fname + " has incorrect link: '" + href + "' (" + href.getClass().getName()
                + ")\nshould be: '" + expected + "' (String)", href, equalTo(expected));
    }//  www .ja va 2  s  .c  o m
}