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, String str) throws IOException, ParseException 

Source Link

Usage

From source file:wuit.common.crawler.search.Crawler.java

public static String doGetHttp(String url) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 12000);
    HttpConnectionParams.setSoTimeout(params, 9000);
    HttpClient httpclient = new DefaultHttpClient(params);
    String rs = "";
    try {//from  w w  w  .  ja  v a  2s  .  c o  m
        //            System.out.println(url);
        HttpGet httpget = new HttpGet(url);

        HttpContext httpContext = new BasicHttpContext();
        //            httpget.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
        httpget.addHeader("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");

        HttpResponse response = httpclient.execute(httpget, httpContext);
        HttpUriRequest realRequest = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
        HttpHost targetHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        url = targetHost.toString() + realRequest.getURI();
        int resStatu = response.getStatusLine().getStatusCode();//? 
        if (resStatu == 200) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                rs = EntityUtils.toString(entity, "iso-8859-1");
                String in_code = getEncoding(rs);
                String encode = getHtmlEncode(rs);
                if (encode.isEmpty()) {
                    httpclient.getConnectionManager().shutdown();
                    return "";
                } else {
                    if (!in_code.toLowerCase().equals("utf-8")
                            && !in_code.toLowerCase().equals(encode.toLowerCase())) {
                        if (!in_code.toLowerCase().equals("iso-8859-1"))
                            rs = new String(rs.getBytes("iso-8859-1"), in_code);
                        if (!encode.toLowerCase().equals(in_code.toLowerCase()))
                            rs = new String(rs.getBytes(in_code), encode);
                    }
                }
                try {
                } catch (RuntimeException ex) {
                    httpget.abort();
                    throw ex;
                } finally {
                    // Closing the input stream will trigger connection release
                    //                    try { instream.close(); } catch (Exception ignore) {}
                }
            }
        }
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
        return rs;
    }
}

From source file:com.mycompany.internalservicecontrollerbatch.ServerCall.java

@Override
public void run() {
    String url = list.getCallToPerform();
    try {//from   w ww.  j a  v  a 2 s.  c om
        HttpClient client = HttpClientBuilder.create().build();
        if (url != null) {

            //HttpPost post = new HttpPost(url);
            //StringEntity entity = new StringEntity("");
            //post.setEntity(entity);

            HttpGet request = new HttpGet(url);
            long start = System.currentTimeMillis();
            HttpResponse response = client.execute(request);
            long end = System.currentTimeMillis();
            //System.out.println("Response Code : "+ response.getStatusLine().getStatusCode() + " index: " +index + " start: " + start + " end: " +end+ " thread name: "+ Thread.currentThread().getName());
            double r = Math.random();
            long wait = Math.round(r * 250);
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString(entity, "UTF-8");
            String printout = "Server Call: " + url + " Response Code : "
                    + response.getStatusLine().getStatusCode() + " Response content: " + responseString;
            list.resolveCall(printout, true);
            Thread.sleep(wait);
        }
    } catch (Exception ex) {
        Logger.getLogger(ServerCall.class.getName()).log(Level.SEVERE, null, ex);
        list.resolveCall("ERROR PERFORMING: " + url, false);
    }

}

From source file:de.escidoc.core.test.sm.ScopeTestBase.java

/**
 * Test creating a Scope./*from ww w  .j a v  a2s . c o  m*/
 *
 * @param dataXml The xml representation of the Scope.
 * @return The created Scope.
 * @throws Exception If anything fails.
 */
public String create(final String dataXml) throws Exception {

    Object result = getScopeClient().create(dataXml);
    String xmlResult = null;
    if (result instanceof HttpResponse) {
        HttpResponse httpRes = (HttpResponse) result;
        xmlResult = EntityUtils.toString(httpRes.getEntity(), HTTP.UTF_8);
        assertHttpStatusOfMethod("", httpRes);
    } else if (result instanceof String) {
        xmlResult = (String) result;
    }
    return xmlResult;
}

From source file:org.elasticsearch.test.rest.client.http.HttpResponse.java

HttpResponse(HttpUriRequest httpRequest, CloseableHttpResponse httpResponse) {
    this.httpRequest = httpRequest;
    this.statusCode = httpResponse.getStatusLine().getStatusCode();
    this.reasonPhrase = httpResponse.getStatusLine().getReasonPhrase();
    if (httpResponse.getEntity() != null) {
        try {//  www.j  a v  a  2 s. c o m
            this.body = EntityUtils.toString(httpResponse.getEntity(), HttpRequestBuilder.DEFAULT_CHARSET);
        } catch (IOException e) {
            EntityUtils.consumeQuietly(httpResponse.getEntity());
            throw new RuntimeException(e);
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    } else {
        this.body = null;
    }
}

From source file:com.psbk.modulperwalian.Controller.ControllerLogin.java

public JSONObject getDataLogin() {
    JSONObject obj = null;/*from w w  w.  ja  va  2s .c o  m*/
    HttpClient httpClient = HttpClientBuilder.create().build();
    String status = null;
    try {
        String url = getIp() + "login";
        HttpPost request = new HttpPost(url);
        StringEntity params = new StringEntity("{request:{\"username\":\"" + getUsername() + "\","
                + "\"password\":\"" + getPassword() + "\" } }");
        request.addHeader("content-type", "application/json");
        request.setEntity(params);

        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        status = EntityUtils.toString(entity, "UTF-8");
        JSONObject result;
        obj = new JSONObject(status);

    } catch (Exception ex) {
        System.out.println("Error karena : " + ex.getMessage());
    }

    return obj;
}

From source file:com.meplato.store2.ApacheHttpResponse.java

/**
 * Instantiates a new instance of ApacheHttpResponse,
 * then close the response./*from  w  w  w  .ja  v  a  2 s .com*/
 *
 * @param response the HTTP response from the ApacheHttpClient.
 * @throws ServiceException if e.g. serialization of the response fails.
 */
public ApacheHttpResponse(CloseableHttpResponse response) throws ServiceException {
    this.statusCode = response.getStatusLine().getStatusCode();

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try {
            ContentType contentType = ContentType.getOrDefault(entity);
            Charset charset = contentType.getCharset();
            this.body = EntityUtils.toString(entity, charset);
        } catch (IOException e) {
            EntityUtils.consumeQuietly(entity);
            throw new ServiceException("Error deserializing data", null, e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
            }
        }
    } else {
        this.body = null;
    }
}

From source file:de.escidoc.core.test.sm.ReportDefinitionTestBase.java

/**
 * Test creating a reportDefinition.// w w  w.  j a va2 s . com
 *
 * @param dataXml The xml representation of the reportDefinition.
 * @return The created ReportDefinition.
 * @throws Exception If anything fails.
 */
@Override
public String create(final String dataXml) throws Exception {

    Object result = getReportDefinitionClient().create(dataXml);
    String xmlResult = null;
    if (result instanceof HttpResponse) {
        HttpResponse httpRes = (HttpResponse) result;
        xmlResult = EntityUtils.toString(httpRes.getEntity(), HTTP.UTF_8);
        assertHttpStatusOfMethod("", httpRes);

    } else if (result instanceof String) {
        xmlResult = (String) result;
    }
    return xmlResult;
}

From source file:com.seleritycorp.common.base.http.client.HttpResponse.java

/**
 * Create HttpResponse from the HttpClient response.
 * //from  w w w .  j  a va2 s.  co  m
 * @param response The HttpClient response to create a HttpResponse from.
 * @throws HttpException if reading the response failed.
 */
@Inject
public HttpResponse(@Assisted org.apache.http.HttpResponse response) throws HttpException {
    this.statusCode = response.getStatusLine().getStatusCode();
    try {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            this.body = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        } else {
            this.body = "";
        }
    } catch (ParseException | IOException e) {
        throw new HttpException("Failed to parse response.", e);
    }
}

From source file:com.apm4all.tracy.TracyCloseableHttpClientPublisher.java

private String extractPostResponse(CloseableHttpResponse response) throws ParseException, IOException {
    StringBuilder sb = new StringBuilder(1024);
    HttpEntity entity = response.getEntity();
    sb.append(response.getStatusLine());
    sb.append(" ");
    sb.append(EntityUtils.toString(entity, StandardCharsets.UTF_8));
    EntityUtils.consume(entity);//from   ww  w  .  j av a2s.c  o  m
    return sb.toString();
}

From source file:org.opencastproject.remotetest.server.resource.CaptureResources.java

public static String captureId(HttpResponse response) throws Exception {
    String pattern = "Unscheduled-\\d+";
    Matcher matcher = Pattern.compile(pattern).matcher(EntityUtils.toString(response.getEntity(), "UTF-8"));
    matcher.find();//w  w w  .  j  av a 2  s.  c  o  m
    return matcher.group();
}