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

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

Introduction

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

Prototype

public static byte[] toByteArray(HttpEntity httpEntity) throws IOException 

Source Link

Usage

From source file:cn.wanghaomiao.seimi.http.hc.HcDownloader.java

private Response renderResponse(HttpResponse httpResponse, Request request, HttpContext httpContext) {
    Response seimiResponse = new Response();
    HttpEntity entity = httpResponse.getEntity();
    seimiResponse.setSeimiHttpType(SeimiHttpType.APACHE_HC);
    seimiResponse.setRealUrl(getRealUrl(httpContext));
    seimiResponse.setUrl(request.getUrl());
    seimiResponse.setRequest(request);//from www  . java 2  s.co  m
    seimiResponse.setMeta(request.getMeta());

    if (entity != null) {
        Header referer = httpResponse.getFirstHeader("Referer");
        if (referer != null) {
            seimiResponse.setReferer(referer.getValue());
        }
        String contentTypeStr = entity.getContentType().getValue().toLowerCase();
        if (contentTypeStr.contains("text") || contentTypeStr.contains("json")
                || contentTypeStr.contains("ajax")) {
            seimiResponse.setBodyType(BodyType.TEXT);
            try {
                seimiResponse.setData(EntityUtils.toByteArray(entity));
                ContentType contentType = ContentType.get(entity);
                Charset charset = contentType.getCharset();
                if (charset == null) {
                    seimiResponse.setContent(new String(seimiResponse.getData(), "ISO-8859-1"));
                    String docCharset = renderRealCharset(seimiResponse);
                    seimiResponse.setContent(
                            new String(seimiResponse.getContent().getBytes("ISO-8859-1"), docCharset));
                    seimiResponse.setCharset(docCharset);
                } else {
                    seimiResponse.setContent(new String(seimiResponse.getData(), charset));
                    seimiResponse.setCharset(charset.name());
                }
            } catch (Exception e) {
                logger.error("no content data");
            }
        } else {
            seimiResponse.setBodyType(BodyType.BINARY);
            try {
                seimiResponse.setData(EntityUtils.toByteArray(entity));
                seimiResponse.setContent(StringUtils.substringAfterLast(request.getUrl(), "/"));
            } catch (Exception e) {
                logger.error("no data can be read from httpResponse");
            }
        }
    }
    return seimiResponse;
}

From source file:pt.brunorene.rawgit.Proxy.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request  servlet request/*from www .j av  a 2  s.  co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException      if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String url = ROOT + request.getRequestURI().replace("/rawgit", "");
    try (OutputStream out = response.getOutputStream()) {
        out.write(client.execute(new HttpGet(url), rsp -> {
            try {
                TikaConfig config = TikaConfig.getDefaultConfig();
                Detector detector = config.getDetector();
                byte[] data = EntityUtils.toByteArray(rsp.getEntity());
                TikaInputStream stream = TikaInputStream.get(data);
                Metadata metadata = new Metadata();
                metadata.add(Metadata.RESOURCE_NAME_KEY, url);
                response.setContentType(detector.detect(stream, metadata).toString());
                return data;
            } catch (IOException ex) {
                log.error(null, ex);
                return new byte[0];
            }
        }));
    }
}

From source file:com.swisscom.refimpl.control.ServiceControl.java

public Subscription retrieveSubscription(String id) {
    try {//from   w  w w  . ja va2 s  .c o m
        log.info("Get info for subscription: " + id);
        List<HttpGet> out = new ArrayList<HttpGet>();
        HttpResponse response = requestor.retrieveSubscriptionByUri(Constants.MERCHANT_ID,
                MIB2Client.SUBSCRIPTIONS_URL + "/" + id, out);
        String r = new String(EntityUtils.toByteArray(response.getEntity()));
        log.info("Got response: " + r);
        return MAPPER.readValue(r, Subscription.class);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.rastating.droidbeard.net.SickbeardAsyncTask.java

protected Bitmap getBitmap(String cmd, List<Pair<String, Object>> params) {
    Bitmap bitmap = null;/*  w  w  w. j  av a2  s.  c om*/
    Preferences preferences = new Preferences(mContext);
    String format = "%sapi/%s/?cmd=%s";

    String uri = String.format(format, preferences.getSickbeardUrl(), preferences.getApiKey(), cmd);
    if (params != null) {
        for (Pair<String, Object> pair : params) {
            uri += "&" + pair.first + "=" + pair.second.toString();
        }
    }

    try {
        HttpClient client = HttpClientManager.INSTANCE.getClient();
        HttpGet request = new HttpGet(uri);
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            byte[] bytes = EntityUtils.toByteArray(entity);
            bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        }
    } catch (MalformedURLException e) {
        mLastException = new SickBeardException("", e);
        e.printStackTrace();
    } catch (IOException e) {
        mLastException = new SickBeardException("", e);
        e.printStackTrace();
    }

    return bitmap;
}

From source file:cache.reverseproxy.LoggingBHttpClientConnection.java

@Override
protected void onResponseReceived(final HttpResponse response) {
    try {/*from  www.j  ava 2  s .  c  om*/
        if (response != null && this.headerlog.isDebugEnabled()) {
            this.headerlog.debug(this.id + " << " + response.getStatusLine().toString());
            final Header[] headers = response.getAllHeaders();
            for (final Header header : headers) {
                this.headerlog.debug(this.id + " << " + header.toString());
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                byte[] entityContent = EntityUtils.toByteArray(entity);
                this.headerlog.debug("~~~~~~~~~~~\r\n" + entityContent);
            }
        }
        /*if (response != null) {
        StringBuilder sb = new StringBuilder();
        sb.append(response.getStatusLine()).append("\r\n");
        for (Header header : response.getAllHeaders()) {
            sb.append(header.toString()).append("\r\n");
        }
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            byte[] entityContent = EntityUtils.toByteArray(entity);
            sb.append("\r\n").append(new String(entityContent));
        }
        System.out.println("===> Response Begin");
        System.out.println(sb.toString());
        System.out.println("===> Response End");
        }*/
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.helger.httpclient.response.ExtendedHttpResponseException.java

@Nonnull
public static ExtendedHttpResponseException create(@Nonnull final StatusLine aStatusLine,
        @Nonnull final HttpResponse aHttpResponse, @Nonnull final HttpEntity aEntity) throws IOException {
    ContentType aContentType = ContentType.get(aEntity);
    if (aContentType == null)
        aContentType = ContentType.DEFAULT_TEXT;

    // Default to ISO-8859-1 internally
    final Charset aCharset = HttpClientHelper.getCharset(aContentType);

    // Consume entity
    final byte[] aResponseBody = EntityUtils.toByteArray(aEntity);

    return new ExtendedHttpResponseException(aStatusLine, aHttpResponse, aResponseBody, aCharset);
}

From source file:org.keycloak.adapters.authorization.cip.HttpClaimInformationPointProvider.java

private InputStream executeRequest(HttpFacade httpFacade) {
    String method = config.get("method").toString();

    if (method == null) {
        method = "GET";
    }/*from  www . java  2  s. c o  m*/

    RequestBuilder builder = null;

    if ("GET".equalsIgnoreCase(method)) {
        builder = RequestBuilder.get();
    } else {
        builder = RequestBuilder.post();
    }

    builder.setUri(config.get("url").toString());

    byte[] bytes = new byte[0];

    try {
        setParameters(builder, httpFacade);

        if (config.containsKey("headers")) {
            setHeaders(builder, httpFacade);
        }

        HttpResponse response = httpClient.execute(builder.build());
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            bytes = EntityUtils.toByteArray(entity);
        }

        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode < 200 || statusCode >= 300) {
            throw new HttpResponseException(
                    "Unexpected response from server: " + statusCode + " / " + statusLine.getReasonPhrase(),
                    statusCode, statusLine.getReasonPhrase(), bytes);
        }

        return new ByteArrayInputStream(bytes);
    } catch (Exception cause) {
        try {
            throw new RuntimeException(
                    "Error executing http method [" + builder + "]. Response : "
                            + StreamUtil.readString(new ByteArrayInputStream(bytes), Charset.forName("UTF-8")),
                    cause);
        } catch (Exception e) {
            throw new RuntimeException("Error executing http method [" + builder + "]", cause);
        }
    }
}

From source file:com.subgraph.vega.internal.http.proxy.ProxyRequestHandler.java

private HttpEntity copyEntity(HttpEntity entity) {
    try {//from   ww  w. j a  v  a  2s.c om
        if (entity == null) {
            return null;
        }
        final ByteArrayEntity newEntity = new ByteArrayEntity(EntityUtils.toByteArray(entity));
        newEntity.setContentEncoding(entity.getContentEncoding());
        newEntity.setContentType(entity.getContentType());
        return newEntity;
    } catch (IOException e) {
        return null;
    }
}

From source file:com.mgmtp.perfload.core.client.web.http.DefaultHttpClientManager.java

/**
 * Executes an HTTP request using the internal {@link HttpClient} instance encapsulating the
 * Http response in the returns {@link ResponseInfo} object. This method takes to time
 * measurements around the request execution, one after calling
 * {@link HttpClient#execute(org.apache.http.client.methods.HttpUriRequest, HttpContext)} (~
 * first-byte measurment) and the other one later after the complete response was read from the
 * stream. These measurements are return as properties of the {@link ResponseInfo} object.
 *///from w  w  w  .  jav  a  2 s. c  om
@Override
public ResponseInfo executeRequest(final HttpRequestBase request, final HttpContext context,
        final UUID requestId) throws IOException {
    request.addHeader(EXECUTION_ID_HEADER, executionId.toString());
    request.addHeader(OPERATION_HEADER, operation);
    request.addHeader(REQUEST_ID_HEADER, requestId.toString());

    String uri = request.getURI().toString();
    String type = request.getMethod();

    TimeInterval tiBeforeBody = new TimeInterval();
    TimeInterval tiTotal = new TimeInterval();

    tiBeforeBody.start();
    tiTotal.start();
    long timestamp = System.currentTimeMillis();

    HttpResponse response = getHttpClient().execute(request, context);
    tiBeforeBody.stop();

    // This actually downloads the response body:
    HttpEntity entity = response.getEntity();
    byte[] body = EntityUtils.toByteArray(entity);
    tiTotal.stop();

    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    String statusMsg = statusLine.getReasonPhrase();
    String responseCharset = EntityUtils.getContentCharSet(entity);
    String contentType = EntityUtils.getContentMimeType(entity);
    String bodyAsString = bodyAsString(contentType, responseCharset, body);

    Header[] headers = response.getAllHeaders();
    Map<String, String> responseHeaders = newHashMapWithExpectedSize(headers.length);
    for (Header header : headers) {
        responseHeaders.put(header.getName(), header.getValue());
    }

    return new ResponseInfo(type, uri, statusCode, statusMsg, responseHeaders, body, bodyAsString,
            responseCharset, contentType, timestamp, tiBeforeBody, tiTotal, executionId, requestId);
}