Example usage for org.apache.http.util EntityUtils toString

List of usage examples for org.apache.http.util EntityUtils toString

Introduction

In this page you can find the example usage for org.apache.http.util EntityUtils toString.

Prototype

public static String toString(HttpEntity httpEntity) throws IOException, ParseException 

Source Link

Usage

From source file:info.smartkit.hairy_batman.demo.MoniterWechatBrowser.java

/**
 * ?URLhtml?//  w  ww .  j a v  a2 s  .c om
 */
@SuppressWarnings("deprecation")
public static String getHttpClientHtml(String url, String code, String userAgent) {
    String html = null;
    @SuppressWarnings("deprecation")
    DefaultHttpClient httpClient = new DefaultHttpClient();// httpClient
    HttpGet httpget = new HttpGet(url);// get?URL
    // Pause for 4 seconds
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
        System.out.println(e1.toString());
    }
    //
    httpget.setHeader("User-Agent", userAgent);
    try {
        // responce
        HttpResponse responce = httpClient.execute(httpget);
        // ?
        int returnCode = responce.getStatusLine().getStatusCode();
        // 200? ?
        if (returnCode == HttpStatus.SC_OK) {
            // 
            HttpEntity entity = responce.getEntity();
            if (entity != null) {
                html = new String(EntityUtils.toString(entity));// html??
            }
        }
    } catch (Exception e) {
        System.out.println("");
        e.printStackTrace();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return html;
}

From source file:com.cognifide.qa.bb.aem.content.CrxRequestSender.java

/**
 * This method sends request to author instance
 *
 * @param request request to send/* www.j  a  v a  2 s . c  om*/
 * @return JsonObject representation of response
 * @throws IOException if response doesn't contain desired message
 */
public JsonObject sendCrxRequest(HttpUriRequest request) throws IOException {
    String resultJson;
    try (CloseableHttpResponse response = httpClient.execute(request)) {
        resultJson = EntityUtils.toString(response.getEntity());
    }
    JsonObject result;
    try {
        result = new JsonParser().parse(resultJson).getAsJsonObject();
    } catch (JsonSyntaxException e) {
        throw new JsonSyntaxException("Unable to parse as Json: " + resultJson, e);
    }
    if (result.get("success").getAsBoolean()) {
        return result;
    }
    throw new IOException(result.get("msg").getAsString());
}

From source file:com.seleritycorp.context.RequestResponseHandler.java

@Override
public JsonObject handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    HttpEntity entity = response.getEntity();
    String responseString = EntityUtils.toString(entity);
    JsonParser parser = new JsonParser();

    // The API does not return partials or some such, so any response that is not a 200,
    // indicates issues.
    if (statusCode != 200) {
        log.trace("Raw response: " + responseString);
        String errorMessage = statusCode + " " + statusLine.getReasonPhrase();
        // Instead of the pure HTTP status information, we try to get a descriptive error
        // message. Context API returns JSON objects that indicate the error. So we
        // opportunistically parse the content and drill down to get the error message. 
        try {//from  w ww. j  ava 2 s . c o  m
            JsonObject json = parser.parse(responseString).getAsJsonObject();
            String hint = "";

            if (json.has("errorCode")) {
                hint = json.toString();
            } else if (json.has("errorMessage")) {
                hint = json.get("errorMessage").getAsString();
            }

            if (hint != null && !hint.isEmpty()) {
                errorMessage += ". (" + hint + ")";
            }
        } catch (Exception e) {
            // Extracting a more detailed error message failed. So we move forward with only the
            // HTTP status line.
        }
        throw new ClientProtocolException("Server responded with " + errorMessage);
    }

    // At this point, response has a 200 HTTP status code.

    String contentType = entity.getContentType().getValue();
    String parameterlessContentType = contentType.split("[; ]", 2)[0];
    if (!"application/json".equals(parameterlessContentType)) {
        // Response is not Json
        log.trace("Raw response: " + responseString);
        throw new ClientProtocolException(
                "Received content type '" + contentType + "' instead of 'application/json'");
    }

    // At this point, response got sent as JSON

    // Parse the string to JSON
    JsonObject ret = parser.parse(responseString).getAsJsonObject();
    return ret;
}

From source file:org.kitodo.data.index.elasticsearch.type.RulesetTypeTest.java

@Test
public void shouldCreateDocument() throws Exception {
    RulesetType rulesetType = new RulesetType();
    Ruleset ruleset = prepareData().get(0);

    HttpEntity document = rulesetType.createDocument(ruleset);
    JSONParser parser = new JSONParser();
    JSONObject rulesetObject = (JSONObject) parser.parse(EntityUtils.toString(document));

    String actual = String.valueOf(rulesetObject.get("title"));
    String excepted = "SLUBDD";
    assertEquals("Ruleset value for title key doesn't match to given plain text!", excepted, actual);

    actual = String.valueOf(rulesetObject.get("file"));
    excepted = "ruleset_slubdd.xml";
    assertEquals("Ruleset value for file key doesn't match to given plain text!", excepted, actual);

    actual = String.valueOf(rulesetObject.get("fileContent"));
    excepted = "";
    assertEquals("Ruleset value for fileContent key doesn't match to given plain text!", excepted, actual);
}

From source file:com.probam.updater.util.HttpStringReader.java

@Override
protected Void doInBackground(String... urls) {
    try {//from w ww .j  a  v a 2  s.c  om
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(urls[0]);
        HttpResponse r = client.execute(get);
        int status = r.getStatusLine().getStatusCode();
        HttpEntity e = r.getEntity();
        if (status == 200) {
            mListener.onReadEnd(EntityUtils.toString(e));
        } else {
            if (e != null)
                e.consumeContent();
            String error = "Server responded with error " + status;
            mListener.onReadError(new Exception(error));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        mListener.onReadError(ex);
    }
    return null;
}

From source file:ADP_Streamline.CURL.java

public void UploadFiles() throws ClientProtocolException, IOException {

    String filePath = "file_path";
    String url = "http://localhost/files";
    File file = new File(filePath);
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("file", new FileBody(file));
    HttpResponse returnResponse = Request.Post(url).body(entity).execute().returnResponse();
    System.out.println("Response status: " + returnResponse.getStatusLine().getStatusCode());
    System.out.println(EntityUtils.toString(returnResponse.getEntity()));
}

From source file:org.elasticsearch.http.DetailedErrorsEnabledIT.java

public void testThatErrorTraceWorksByDefault() throws IOException {
    try {//w w w .  ja  v a  2 s  . c  o m
        getRestClient().performRequest("DELETE", "/", Collections.singletonMap("error_trace", "true"));
        fail("request should have failed");
    } catch (ResponseException e) {
        Response response = e.getResponse();
        assertThat(response.getHeader("Content-Type"), containsString("application/json"));
        assertThat(EntityUtils.toString(response.getEntity()),
                containsString("\"stack_trace\":\"[Validation Failed: 1: index / indices is missing;]; "
                        + "nested: ActionRequestValidationException[Validation Failed: 1:"));
    }

    try {
        getRestClient().performRequest("DELETE", "/");
        fail("request should have failed");
    } catch (ResponseException e) {
        Response response = e.getResponse();
        assertThat(response.getHeader("Content-Type"), containsString("application/json; charset=UTF-8"));
        assertThat(EntityUtils.toString(response.getEntity()),
                not(containsString("\"stack_trace\":\"[Validation Failed: 1: index / indices is missing;]; "
                        + "nested: ActionRequestValidationException[Validation Failed: 1:")));
    }
}

From source file:com.droidworks.asynctask.AbsTinyUrlAsyncTask.java

@Override
protected String doInBackground(String... url) {
    String result = null;//from   ww  w  .j  av a  2 s. c  o m

    try {
        HttpGet getMethod = new HttpGet(TINY_URL_API + url[0]);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpUtils.setConnectionTimeout(httpClient, 10);
        HttpResponse response = httpClient.execute(getMethod);
        result = EntityUtils.toString(response.getEntity());
    } catch (Exception e) {
        Log.e(getClass().getName(), "Error transforming url", e);
    }

    return result;
}

From source file:org.keycloak.testsuite.util.matchers.HttpResponseStatusCodeMatcher.java

@Override
public void describeMismatch(Object item, Description description) {
    Description d = description.appendText("was ").appendValue(item).appendText(" with entity ");
    try {/* ww w . ja va  2 s  .  com*/
        d.appendText(EntityUtils.toString(((HttpResponse) item).getEntity()));
    } catch (IOException e) {
        d.appendText("<Cannot decode entity: " + e.getMessage() + ">");
    }
}

From source file:self.philbrown.javaQuery.ScriptResponseHandler.java

@Override
public ScriptResponse handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    StatusLine statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() >= 300) {
        Log.e("javaQuery",
                "HTTP Response Error " + statusLine.getStatusCode() + ":" + statusLine.getReasonPhrase());
        return null;
    }//ww w .  j av a2s.c o m

    HttpEntity entity = response.getEntity();
    if (entity == null)
        return null;

    ScriptResponse script = new ScriptResponse();
    script.text = EntityUtils.toString(entity);
    //new line characters currently represent a new command. 
    //Although one file can be all one line, it will be executed as a shell script.
    //for something else, the first line should contain be: #!<shell>\n, where <shell> points
    //to the shell that should be used.
    String[] commands = script.text.split("\n");
    script.script = new Script(commands);
    try {
        script.output = script.script.execute();
    } catch (Throwable t) {
        //could not execute script
        script.output = null;
    }
    return script;
}