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:de.xwic.appkit.core.remote.client.URemoteAccessClient.java

/**
 * @param param/*from   w  w  w  .  ja va 2s . com*/
 * @param config
 * @return
 */
public static byte[] postRequest(final IRequestHelper helper, final RemoteSystemConfiguration config) {
    CloseableHttpResponse response = null;
    try {

        CloseableHttpClient client = PoolingHttpConnectionManager.getInstance().getClientInstance(config);
        HttpPost post = new HttpPost(helper.getTargetUrl());
        post.setEntity(helper.getHttpEntity());

        response = client.execute(post);

        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new RemoteDataAccessException(response.getStatusLine().getReasonPhrase());
        }
        return EntityUtils.toByteArray(response.getEntity());
    } catch (RemoteDataAccessException re) {
        throw re;
    } catch (Exception e) {
        throw new RemoteDataAccessException(e);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}

From source file:com.jonbanjo.cups.operations.HttpPoster.java

static OperationResult sendRequest(URL url, ByteBuffer ippBuf, InputStream documentStream, final AuthInfo auth)
        throws IOException {

    final OperationResult opResult = new OperationResult();

    if (ippBuf == null) {
        return null;
    }/* w  ww  .ja  va 2  s.  c o m*/

    if (url == null) {
        return null;
    }

    DefaultHttpClient client = new DefaultHttpClient();

    // will not work with older versions of CUPS!
    client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    client.getParams().setParameter("http.socket.timeout", SOCKET_TIMEOUT);
    client.getParams().setParameter("http.connection.timeout", CONNECTION_TIMEOUT);
    client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    client.getParams().setParameter("http.method.response.buffer.warnlimit", new Integer(8092));
    // probabaly not working with older CUPS versions
    client.getParams().setParameter("http.protocol.expect-continue", Boolean.valueOf(true));

    HttpPost httpPost;

    try {
        httpPost = new HttpPost(url.toURI());
    } catch (Exception e) {
        System.out.println(e.toString());
        return null;
    }

    httpPost.getParams().setParameter("http.socket.timeout", SOCKET_TIMEOUT);

    byte[] bytes = new byte[ippBuf.limit()];
    ippBuf.get(bytes);

    ByteArrayInputStream headerStream = new ByteArrayInputStream(bytes);
    // If we need to send a document, concatenate InputStreams
    InputStream inputStream = headerStream;
    if (documentStream != null) {
        inputStream = new SequenceInputStream(headerStream, documentStream);
    }

    // set length to -1 to advice the entity to read until EOF
    InputStreamEntity requestEntity = new InputStreamEntity(inputStream, -1);

    requestEntity.setContentType(IPP_MIME_TYPE);
    httpPost.setEntity(requestEntity);

    if (auth.reason == AuthInfo.AUTH_REQUESTED) {
        AuthHeader.makeAuthHeader(httpPost, auth);
        if (auth.reason == AuthInfo.AUTH_OK) {
            httpPost.addHeader(auth.getAuthHeader());
            //httpPost.addHeader("Authorization", "Basic am9uOmpvbmJveQ==");
        }
    }

    ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
        @Override
        public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            if (response.getStatusLine().getStatusCode() == 401) {
                auth.setHttpHeader(response.getFirstHeader("WWW-Authenticate"));
            } else {
                auth.reason = AuthInfo.AUTH_OK;
            }
            HttpEntity entity = response.getEntity();
            opResult.setHttResult(response.getStatusLine().toString());
            if (entity != null) {
                return EntityUtils.toByteArray(entity);
            } else {
                return null;
            }
        }
    };

    if (url.getProtocol().equals("https")) {

        Scheme scheme = JfSSLScheme.getScheme();
        if (scheme == null)
            return null;
        client.getConnectionManager().getSchemeRegistry().register(scheme);
    }

    byte[] result = client.execute(httpPost, handler);
    //String test = new String(result);
    IppResponse ippResponse = new IppResponse();

    opResult.setIppResult(ippResponse.getResponse(ByteBuffer.wrap(result)));
    opResult.setAuthInfo(auth);
    client.getConnectionManager().shutdown();
    return opResult;
}

From source file:net.facework.core.http.ModAssetServer.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {
    AbstractHttpEntity body = null;/*from   w w w  .j  a  v  a 2s .  c  o m*/

    final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }

    final String url = URLDecoder.decode(request.getRequestLine().getUri());
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        byte[] entityContent = EntityUtils.toByteArray(entity);
        Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length);
    }

    final String location = "www" + (url.equals("/") ? "/index.htm" : url);
    response.setStatusCode(HttpStatus.SC_OK);

    try {
        Log.i(TAG, "Requested: \"" + url + "\"");

        // Compares the Last-Modified date header (if present) with the If-Modified-Since date
        if (request.containsHeader("If-Modified-Since")) {
            try {
                Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue());
                if (date.compareTo(mServer.mLastModified) <= 0) {
                    // The file has not been modified
                    response.setStatusCode(HttpStatus.SC_NOT_MODIFIED);
                    return;
                }
            } catch (DateParseException e) {
                e.printStackTrace();
            }
        }

        // We determine if the asset is compressed
        try {
            AssetFileDescriptor afd = mAssetManager.openFd(location);

            // The asset is not compressed
            FileInputStream fis = new FileInputStream(afd.getFileDescriptor());
            fis.skip(afd.getStartOffset());
            body = new InputStreamEntity(fis, afd.getDeclaredLength());

            Log.d(TAG, "Serving uncompressed file " + "www" + url);

        } catch (FileNotFoundException e) {

            // The asset may be compressed
            // AAPT compresses assets so first we need to uncompress them to determine their length
            InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000);
            byte[] tmp = new byte[4096];
            int length = 0;
            while ((length = stream.read(tmp)) != -1)
                buffer.write(tmp, 0, length);
            body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size());
            stream.close();

            Log.d(TAG, "Serving compressed file " + "www" + url);

        }

        body.setContentType(getMimeMediaType(url) + "; charset=UTF-8");
        response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified));

    } catch (IOException e) {
        // File does not exist
        response.setStatusCode(HttpStatus.SC_NOT_FOUND);
        body = new EntityTemplate(new ContentProducer() {
            @Override
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                writer.write("<html><body><h1>");
                writer.write("File ");
                writer.write("www" + url);
                writer.write(" not found");
                writer.write("</h1></body></html>");
                writer.flush();
            }
        });
        Log.d(TAG, "File " + "www" + url + " not found");
        body.setContentType("text/html; charset=UTF-8");
    }

    response.setEntity(body);

}

From source file:de.yaio.services.metaextract.client.MetaExtractClient.java

/**
 * create a metaextract of the url// w ww . j  a v  a 2  s .c o m
 * @return                       returns the metaextract as JSON
 * @param url                    url to make a metaextract from
 * @throws IOExceptionWithCause  if something went wrong with metaextract
 * @throws IOException           if something went wrong with response-io
 */
public byte[] getMetaExtractFromUrl(final String url) throws IOExceptionWithCause, IOException {
    // get metadata from url
    Map<String, String> params = new HashMap<String, String>();
    params.put("lang", "de");
    params.put("url", url);

    // call url
    String baseUrl = metaextracturl + "/getByUrl";
    HttpEntity entity;
    HttpResponse response;
    response = HttpUtils.callPostUrlPure(baseUrl, metaextractusername, metaextractpassword, params, null, null);
    entity = response.getEntity();

    // check response
    int retCode = response.getStatusLine().getStatusCode();
    if (retCode < 200 || retCode > 299) {
        throw new IOExceptionWithCause("error while extracting metadata for url", url,
                new IOException("illegal reponse:" + response.getStatusLine() + " for baseurl:" + baseUrl
                        + " with url:" + url + " response:" + EntityUtils.toString(entity)));
    }

    return EntityUtils.toByteArray(entity);
}

From source file:com.wifi.brainbreaker.mydemo.http.ModAssetServer.java

public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {
    AbstractHttpEntity body = null;//w w  w. jav  a2  s .  co m

    final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }

    final String url = URLDecoder.decode(request.getRequestLine().getUri());
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        byte[] entityContent = EntityUtils.toByteArray(entity);
        Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length);
    }

    final String location = "www" + (url.equals("/") ? "/index.htm" : url);
    response.setStatusCode(HttpStatus.SC_OK);

    try {
        Log.i(TAG, "Requested: \"" + url + "\"");

        // Compares the Last-Modified date header (if present) with the If-Modified-Since date
        if (request.containsHeader("If-Modified-Since")) {
            try {
                Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue());
                if (date.compareTo(mServer.mLastModified) <= 0) {
                    // The file has not been modified
                    response.setStatusCode(HttpStatus.SC_NOT_MODIFIED);
                    return;
                }
            } catch (DateParseException e) {
                e.printStackTrace();
            }
        }

        // We determine if the asset is compressed
        try {
            AssetFileDescriptor afd = mAssetManager.openFd(location);

            // The asset is not compressed
            FileInputStream fis = new FileInputStream(afd.getFileDescriptor());
            fis.skip(afd.getStartOffset());
            body = new InputStreamEntity(fis, afd.getDeclaredLength());

            Log.d(TAG, "Serving uncompressed file " + "www" + url);

        } catch (FileNotFoundException e) {

            // The asset may be compressed
            // AAPT compresses assets so first we need to uncompress them to determine their length
            InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000);
            byte[] tmp = new byte[4096];
            int length = 0;
            while ((length = stream.read(tmp)) != -1)
                buffer.write(tmp, 0, length);
            body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size());
            stream.close();

            Log.d(TAG, "Serving compressed file " + "www" + url);

        }

        body.setContentType(getMimeMediaType(url) + "; charset=UTF-8");
        response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified));

    } catch (IOException e) {
        // File does not exist
        response.setStatusCode(HttpStatus.SC_NOT_FOUND);
        body = new EntityTemplate(new ContentProducer() {
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                writer.write("<html><body><h1>");
                writer.write("File ");
                writer.write("www" + url);
                writer.write(" not found");
                writer.write("</h1></body></html>");
                writer.flush();
            }
        });
        Log.d(TAG, "File " + "www" + url + " not found");
        body.setContentType("text/html; charset=UTF-8");
    }

    response.setEntity(body);

}

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

public Service retrieveService(String id) {
    try {/*  w w w  .j a  v a  2  s  .  com*/
        log.info("Get info for service: " + id);
        HttpResponse response = requestor.retrieveServiceByUri(Constants.MERCHANT_ID,
                MIB2Client.SERVICES_URL + "/" + id);
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(EntityUtils.toByteArray(response.getEntity()), Service.class);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:cn.com.lowe.android.tools.net.response.BinaryHttpResponseHandler.java

@Override
public void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    byte[] responseBody = null;
    if (contentTypeHeaders.length != 1) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(),
                "None, or more than one, Content-Type Header found!"), responseBody);
        return;//from   w  w  w.ja va 2  s .c o  m
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : mAllowedContentTypes) {
        if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
            foundAllowedContentType = true;
        }
    }
    if (!foundAllowedContentType) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"),
                responseBody);
        return;
    }
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
        }
        responseBody = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        sendFailureMessage(e, responseBody);
    }

    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody);
    } else {
        sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
    }
}

From source file:org.phpmaven.pear.impl.Helper.java

/**
 * Returns the binary file contents./*from  w w w.j  a  v  a2  s .  c o m*/
 * @param uri URI of the resource.
 * @return the files content.
 * @throws IOException thrown on errors.
 */
public static byte[] getBinaryFileContents(String uri) throws IOException {
    // is it inside the local filesystem?
    if (uri.startsWith("file://")) {
        final File channelFile = new File(uri.substring(7));

        final byte[] result = new byte[(int) channelFile.length()];
        final FileInputStream fis = new FileInputStream(channelFile);
        fis.read(result);
        return result;
    }

    // try http connection
    final HttpClient client = new DefaultHttpClient();
    final HttpGet httpget = new HttpGet(uri);
    final HttpResponse response = client.execute(httpget);
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException("Invalid http status: " + response.getStatusLine().getStatusCode() + " / "
                + response.getStatusLine().getReasonPhrase());
    }
    final HttpEntity entity = response.getEntity();
    if (entity == null) {
        throw new IOException("Empty response.");
    }
    return EntityUtils.toByteArray(entity);
}

From source file:org.aesop.serializer.batch.reader.UserInfoServiceReader.java

/**
 * Returns a number of {@link UserInfo} instances looked up from a service end-point.
 * Note : The end-point and parameters used here are very specific to this sample. Also the code is mostly for testing and production 
 * ready (no Http connection pools etc.) 
 * @see org.trpr.platform.batch.spi.spring.reader.BatchItemStreamReader#batchRead(org.springframework.batch.item.ExecutionContext)
 *///from w w  w.  jav  a2s  .  c o m
public UserInfo[] batchRead(ExecutionContext context)
        throws Exception, UnexpectedInputException, ParseException {
    objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    UserInfo[] results = new UserInfo[PHONE_NUMBERS.length];
    for (int i = 0; i < PHONE_NUMBERS.length; i++) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet executionGet = new HttpGet(SERVICE_URL);
        URIBuilder uriBuilder = new URIBuilder(executionGet.getURI());
        uriBuilder.addParameter("primary_phone", PHONE_NUMBERS[i]);
        uriBuilder.addParameter("require", "{\"preferences\":true,\"addresses\":true}");
        ((HttpRequestBase) executionGet).setURI(uriBuilder.build());
        HttpResponse httpResponse = httpclient.execute(executionGet);
        String response = new String(EntityUtils.toByteArray(httpResponse.getEntity()));
        SearchResult searchResult = objectMapper.readValue(response, SearchResult.class);
        results[i] = searchResult.results[0]; // we take only the first result
    }
    return results;
}

From source file:com.streamreduce.util.WebHDFSClient.java

/**
 * Reads the contents of the target path in connection URL, returning a byte[].
 *
 * @param target the target path to be read.  If target is null or blank, it is ignored.
 * @return byte[]//w  ww  .  j  a  va2  s .  c  om
 * @throws IOException if there is an error reading the file from the server
 */
public byte[] readFile(String target) throws IOException {
    target = StringUtils.isNotBlank(target) ? target : "";
    HttpGet method = new HttpGet(String.format("%s%s?op=OPEN&user.name=%s", url, target, username));

    byte[] responseBody = null;
    try {
        HttpResponse response = httpClient.execute(method);
        StatusLine status = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        if (status.getStatusCode() != 200) {
            if (entity != null) {
                EntityUtils.consume(entity);
            }
            throw new IOException(String.format("Error returned from server. Status: %s - %s",
                    status.getStatusCode(), status.getReasonPhrase()));
        }
        if (entity != null) {
            responseBody = EntityUtils.toByteArray(entity);
        }
    } catch (IOException e) {
        method.abort();
        throw e;
    }

    return responseBody;
}