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:com.ajah.http.Http.java

/**
 * Return the body of the response as a byte array (such as an image).
 * // w w w.j ava 2 s. co m
 * @param uri
 *            The URI to fetch.
 * @return The response body as a String.
 * @throws IOException
 *             If the response could not be completed.
 * @throws UnexpectedResponseCode
 *             If an unexpected/illegal response status is issued.
 * @throws NotFoundException
 *             If the resource could not be found at the URI (404).
 */
public static byte[] getBytes(final URI uri) throws IOException, NotFoundException, UnexpectedResponseCode {
    return EntityUtils.toByteArray(internalGet(uri));
}

From source file:ru.algorithmist.jquant.infr.GAEHTTPClient.java

@Override
public String getContent(String url) throws IOException {
    logger.info("Query " + url);
    HttpResponse resp = client.execute(new HttpGet(url));
    HttpEntity entity = resp.getEntity();
    String encoding = EntityUtils.getContentCharSet(entity);

    logger.info("Character encoding  " + encoding);
    if (encoding == null) {
        encoding = "UTF-8";
    }/*from  w  w w .  ja va2 s . c o  m*/
    return new String(EntityUtils.toByteArray(entity), encoding);
}

From source file:it.unicaradio.android.utils.NetworkUtils.java

public static byte[] httpPost(String url, byte[] postData, String contentType)
        throws ClientProtocolException, IOException, HttpException {
    HttpParams httpParams = new BasicHttpParams();

    HttpPost post = new HttpPost(url);
    post.setEntity(new ByteArrayEntity(postData));
    post.addHeader("Content-Type", contentType);

    HttpClient client = new DefaultHttpClient(httpParams);
    HttpResponse response = client.execute(post);

    HttpEntity httpEntity = response.getEntity();
    if (httpEntity == null) {
        throw new HttpException("No answer from server.");
    }// w  ww .  java 2s  .  c  o  m

    return EntityUtils.toByteArray(httpEntity);
}

From source file:com.olacabs.fabric.executor.impl.HttpMetadataSource.java

@Override
public ComputationSpec load(String url) throws Exception {
    //First resolve to a real host-port combo if it's Mesos DNS
    String specEndpoint = url;/*from  w  ww .ja  v  a  2  s  . c om*/
    String specHost = specEndpoint.split("//")[1].split("/")[0];

    if (specHost.endsWith(".")) {
        // Need to do a srv record resolution
        List<LookupResult> results = dnsResolver.dnsSrvLookup(specHost);

        if (!results.isEmpty()) {
            specHost = InetAddress.getByName(results.get(0).host()).getHostAddress() + ":"
                    + results.get(0).port();
            LOGGER.info("Setting spec host to: " + specHost);
        } else {
            throw new RuntimeException(String.format("Dns Srv Resolution for spec host failed: %s", specHost));
        }
        specEndpoint = specEndpoint.split("//")[0] + "//" + specHost + "/"
                + specEndpoint.split("//")[1].replaceFirst(".*\\./", "");
    }
    HttpGet getRequest = new HttpGet(specEndpoint);
    HttpResponse response = httpClient.execute(getRequest);
    if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
        throw new Exception("Received: " + response.getStatusLine().getStatusCode() + " from spec url: " + url);
    }

    return mapper.readValue(EntityUtils.toByteArray(response.getEntity()), ComputationSpec.class);
}

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

public List<Subscription> retrieveSubscriptionsForMsisdn(String msisdn) {
    try {//from  ww  w .ja  v  a  2 s.  com
        HttpResponse response = requestor.retrieveSubscriptions(msisdn, Constants.MERCHANT_ID, null);
        int rCode = response.getStatusLine().getStatusCode();
        log.info("Got response code [" + rCode + "] ");
        if (rCode == HTTP_NO_CONTENT) {
            return new ArrayList<Subscription>();
        } else {
            String r = new String(EntityUtils.toByteArray(response.getEntity()));
            log.info("Got response: " + r);
            Subscriptions srvs = MAPPER.readValue(r, Subscriptions.class);
            return srvs.getSubscriptions();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:org.aliuge.crawler.page.Page.java

/**
 * Loads the content of this page from a fetched HttpEntity.
 *///from w w  w . jav  a  2s .c om
public void load(HttpEntity entity) throws Exception {

    contentType = null;
    Header type = entity.getContentType();
    if (type != null) {
        contentType = type.getValue();
    }

    contentEncoding = null;
    Header encoding = entity.getContentEncoding();
    if (encoding != null) {
        contentEncoding = encoding.getValue();
    }

    Charset charset = ContentType.getOrDefault(entity).getCharset();
    if (charset != null) {
        contentCharset = charset.displayName();
    }

    contentData = EntityUtils.toByteArray(entity);
    // headcharsetmeta?
    if (null == contentCharset || "" == contentCharset) {
        int length = contentData.length;
        if (length > 2048) {
            length = 2048;
        }
        String html = new String(contentData, 0, 2048);
        contentCharset = matchCharset(html.toLowerCase());
    }
}

From source file:nl.mineleni.cbsviewer.jsp.JSPIntegrationTest.java

/**
 * response validatie test tegen validator.nu
 * //  w ww .  j  av a2s . c o m
 * @param response
 *            test object
 * @throws Exception
 *             als er een fout optreedt tijdens de test.
 */
protected void boilerplateValidationTests(final HttpResponse response) throws Exception {

    final String body = new String(EntityUtils.toByteArray(response.getEntity()), "UTF-8");
    assertNotNull("De response body mag geen null zijn.", body);
    assertTrue("Response body dient met juiste prolog te starten.", body.startsWith(RESPONSEPROLOG));

    // online validation
    final HttpPost validatorrequest = new HttpPost(
            /* "http://html5.validator.nu/" */
            "https://validator.nu/");
    final HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.STRICT)
            .addTextBody("content", body, ContentType.APPLICATION_XHTML_XML)
            .addTextBody("schema",
                    "http://s.validator.nu/xhtml5-rdfalite.rnc http://s.validator.nu/html5/assertions.sch http://c.validator.nu/all/",
                    ContentType.DEFAULT_TEXT)
            .addTextBody("level", "error", ContentType.DEFAULT_TEXT)
            .addTextBody("parser", "xml", ContentType.DEFAULT_TEXT)
            // .addTextBody("parser", "html5", ContentType.DEFAULT_TEXT)
            .addTextBody("out", "json", ContentType.DEFAULT_TEXT).build();
    validatorrequest.setEntity(entity);
    final HttpResponse validatorresponse = validatorclient.execute(validatorrequest);

    assertThat("Validator response code.", Integer.valueOf(validatorresponse.getStatusLine().getStatusCode()),
            equalTo(SC_OK));

    final String validatorbody = new String(EntityUtils.toByteArray(validatorresponse.getEntity()), "UTF-8");
    LOGGER.debug("validator body:\n" + validatorbody);

    // controle op succes paragraaf in valadator response
    assertTrue("(X)HTML is niet geldig.", validatorbody.contains("<p class=\"success\">"));
}

From source file:org.artags.android.app.widget.HttpUtils.java

/**
 * Load a bitmap//  w w w  .j a  v a  2 s . c  o m
 * @param url The URL
 * @return The bitmap
 */
public static Bitmap loadBitmap(String url) {
    try {
        final HttpClient httpClient = getHttpClient();
        final HttpResponse resp = httpClient.execute(new HttpGet(url));
        final HttpEntity entity = resp.getEntity();

        final int statusCode = resp.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK || entity == null) {
            return null;
        }

        final byte[] respBytes = EntityUtils.toByteArray(entity);
        // Decode the bytes and return the bitmap.
        BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
        decodeOptions.inSampleSize = 1;
        return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions);
    } catch (Exception e) {
        Log.w(TAG, "Problem while loading image: " + e.toString(), e);
    }
    return null;

}

From source file:ch.tatool.core.module.creator.FileDownloadWorker.java

/** Loads the module file from the data server using the provided code. */
public void loadFile(String url, int timeout) {
    // give it a timeout to ensure the user does not wait forever in case of connectivity problems
    HttpParams params = new BasicHttpParams();
    if (timeout > 0) {
        HttpConnectionParams.setConnectionTimeout(params, timeout);
        HttpConnectionParams.setSoTimeout(params, timeout);
    }/*from w w  w .  j a v a  2s.  c o m*/

    // remove whitespaces since they are not allowed
    url = url.replaceAll("\\s+", "").trim();

    // create a http client
    DefaultHttpClient httpclient = new DefaultHttpClient(params);
    HttpGet httpGet = new HttpGet(url);

    errorTitle = null;
    errorText = null;
    file = null;
    try {
        HttpResponse response = httpclient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            errorTitle = messages.getString("General.errorMessage.windowTitle.error");
            errorText = messages.getString("DataExportError.online.http");
            errorText += "\n" + response.getStatusLine().getReasonPhrase() + " ("
                    + response.getStatusLine().getStatusCode() + ")";
        } else {
            // copy the response into a temporary file
            HttpEntity entity = response.getEntity();
            byte[] data = EntityUtils.toByteArray(entity);
            File tmpFile = File.createTempFile("tatool_module", "tmp");
            FileUtils.writeByteArrayToFile(tmpFile, data);
            tmpFile.deleteOnExit();
            this.file = tmpFile;
        }
    } catch (IOException ioe) {
        errorTitle = messages.getString("General.errorMessage.windowTitle.error");
        errorText = messages.getString("DataExportError.online.http");
    } finally {
        // make sure we close the connection manager
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:tv.icntv.common.HttpClientUtil.java

/**
 * Get content by url as string/*ww  w . j  a v  a2 s .com*/
 *
 * @param url original url
 * @return page content
 * @throws java.io.IOException
 */
public static String getContent(String url) throws IOException {
    // construct request
    HttpGet request = new HttpGet(url);
    request.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"));

    request.setConfig(RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
            .setSocketTimeout(SOCKET_TIMEOUT).build());
    // construct response handler
    ResponseHandler<String> handler = new ResponseHandler<String>() {
        @Override
        public String handleResponse(final HttpResponse response) throws IOException {
            StatusLine status = response.getStatusLine();
            // status
            if (status.getStatusCode() != HttpStatus.SC_OK) {
                throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase());
            }
            // get encoding in header
            String encoding = getPageEncoding(response);
            boolean encodingFounded = true;
            if (Strings.isNullOrEmpty(encoding)) {
                encodingFounded = false;
                encoding = "iso-8859-1";
            }
            // get content and find real encoding
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                return null;
            }
            // get content
            byte[] contentBytes = EntityUtils.toByteArray(entity);
            if (contentBytes == null) {
                return null;
            }
            // found encoding
            if (encodingFounded) {
                return new String(contentBytes, encoding);
            }
            // attempt to discover encoding
            String rawContent = new String(contentBytes, DEFAULT_ENCODING);
            Matcher matcher = PATTERN_HTML_CHARSET.matcher(rawContent);
            if (matcher.find()) {
                String realEncoding = matcher.group(1);
                if (!encoding.equalsIgnoreCase(realEncoding)) {
                    // bad luck :(
                    return new String(rawContent.getBytes(encoding), realEncoding);
                }
            }
            // not found right encoding :)
            return rawContent;
        }
    };
    // execute
    CloseableHttpClient client = HttpClientHolder.getClient();
    return client.execute(request, handler);
}