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.corebase.android.framework.http.client.MyHttpRequest.java

protected byte[] getByteArrayAndSendMessage(HttpResponse response) throws IOException {
    byte[] responseBody = null;
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    if (contentTypeHeaders.length != 1) {
        return null;
    }//from  w w w  .  j a va  2  s  .c  om
    HttpEntity entity = null;
    HttpEntity temp = response.getEntity();
    if (temp != null) {
        entity = new BufferedHttpEntity(temp);
    }
    responseBody = EntityUtils.toByteArray(entity);

    return responseBody;
}

From source file:lynxtools.async_download.BinaryHttpResponseHandler.java

@Override
void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();

    Header[] contentTypeHeaders = response.getHeaders("Content-Type");

    byte[] responseBody = null;

    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(),
                "None, or more than one, Content-Type Header found!"), responseBody);
        return;/*from  w  w  w  .j  a va2 s .c  om*/
    }

    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
        }

        responseBody = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        sendFailureMessage(e, (byte[]) null);
    }

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

From source file:de.yaio.services.webshot.client.WebshotClient.java

/**
 * create a webshot of the url//  w ww . j a va2s.  c o m
 * @return                       returns the webshot as png-file
 * @param url                    url to make a webshot from
 * @param format                 format of the webshot
 * @throws IOExceptionWithCause  if something logical went wrong
 * @throws IOException           if something physical went wrong
 */
public byte[] getWebShotFromUrl(final String url, final FORMAT format)
        throws IOExceptionWithCause, IOException {
    // get image from url
    Map<String, String> params = new HashMap<String, String>();
    params.put("url", url);

    // call url
    String baseUrl = webshoturl + "/url2" + format;
    HttpEntity entity;
    HttpResponse response;
    response = HttpUtils.callPostUrlPure(baseUrl, webshotusername, webshotpassword, params, null, null);
    entity = response.getEntity();

    // check response
    int retCode = response.getStatusLine().getStatusCode();
    if (retCode < 200 || retCode > 299) {
        throw new IOExceptionWithCause("error while calling webshot 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.github.horrorho.inflatabledonkey.responsehandler.PropertyListResponseHandler.java

@Override
public T handleEntity(HttpEntity entity) throws IOException {
    try {// w  w  w.  j  ava  2s . co  m
        return (T) PropertyListParser.parse(EntityUtils.toByteArray(entity));

    } catch (ClassCastException | IOException | PropertyListFormatException | ParseException
            | ParserConfigurationException | SAXException ex) {

        throw new BadDataException("Failed to parse property list", ex);
    }
}

From source file:eu.fthevenet.binjr.data.adapters.HttpDataAdapterBase.java

@Override
public byte[] onCacheMiss(String path, Instant begin, Instant end) throws DataAdapterException {
    return doHttpGet(craftFetchUri(path, begin, end), new AbstractResponseHandler<byte[]>() {
        @Override/*w ww . j  a  va  2  s  .c  o m*/
        public byte[] handleEntity(HttpEntity entity) throws IOException {
            return EntityUtils.toByteArray(entity);
        }
    });
}

From source file:org.red5.client.net.rtmpt.RTMPTClientConnector.java

public void run() {
    HttpPost post = null;/*from w w w.ja v a 2s.c o  m*/
    try {
        RTMPTClientConnection connection = openConnection();
        while (!connection.isClosing() && !stopRequested) {
            IoBuffer toSend = connection.getPendingMessages(SEND_TARGET_SIZE);
            int limit = toSend != null ? toSend.limit() : 0;
            if (limit > 0) {
                post = makePost("send");
                post.setEntity(new InputStreamEntity(toSend.asInputStream(), limit));
                post.addHeader("Content-Type", CONTENT_TYPE);
            } else {
                post = makePost("idle");
                post.setEntity(ZERO_REQUEST_ENTITY);
            }
            // execute
            HttpResponse response = httpClient.execute(targetHost, post);
            // check for error
            checkResponseCode(response);
            // handle data
            byte[] received = EntityUtils.toByteArray(response.getEntity());
            IoBuffer data = IoBuffer.wrap(received);
            if (data.limit() > 0) {
                data.skip(1); // XXX: polling interval lies in this byte
            }
            List<?> messages = connection.decode(data);
            if (messages == null || messages.isEmpty()) {
                try {
                    // XXX handle polling delay
                    Thread.sleep(250);
                } catch (InterruptedException e) {
                    if (stopRequested) {
                        post.abort();
                        break;
                    }
                }
                continue;
            }
            IoSession session = new DummySession();
            session.setAttribute(RTMPConnection.RTMP_CONNECTION_KEY, connection);
            session.setAttribute(ProtocolState.SESSION_KEY, connection.getState());
            for (Object message : messages) {
                try {
                    client.messageReceived(message, session);
                } catch (Exception e) {
                    log.error("Could not process message.", e);
                }
            }
        }
        finalizeConnection();
        client.connectionClosed(connection, connection.getState());
    } catch (Throwable e) {
        log.debug("RTMPT handling exception", e);
        client.handleException(e);
        if (post != null) {
            post.abort();
        }
    }
}

From source file:com.flipkart.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 ww  w.ja va 2  s.  c  o m
public UserInfo[] batchRead(ExecutionContext context)
        throws Exception, UnexpectedInputException, ParseException {
    if (!hasRun) {
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        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
        }
        hasRun = true;
    } else {
        if (modIndex < 0) {
            return null;
        }
        System.out.println("Modifiying response object at index : " + modIndex);
        results[modIndex].setFirst_name("Regu " + modIndex);
        results[modIndex].setLast_name("B " + modIndex);
        results[modIndex].setPrimary_email("regunathb@gmail.com" + modIndex);
        results[modIndex].setPrimary_phone("9886693892" + modIndex);
        if (results[modIndex].getPreferences() != null && results[modIndex].getPreferences().size() > 0) {
            Iterator<String> it = results[modIndex].getPreferences().keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                UserPreferencesInfo upi = results[modIndex].getPreferences().get(key);
                Map<String, Object> values = new HashMap<String, Object>();
                values.put("communication", "email");
                values.put("address", "home");
                upi.setValue(values);
            }
        }
        modIndex -= 1;
    }
    return results;
}

From source file:org.jcodec.player.filters.http.Downloader.java

public synchronized MediaInfo downloadMediaInfo() throws IOException {
    HttpGet get = new HttpGet(url);
    get.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
    HttpResponse response = privilegedExecute(client, get);
    if (response.getStatusLine().getStatusCode() != 200) {
        if (response.getEntity() != null)
            EntityUtils.toByteArray(response.getEntity());
        return null;
    }//from   w  w  w .  ja  v  a2s  .  c o m
    return parseMediaInfo(EntityUtils.toString(response.getEntity()));
}

From source file:com.hippoapp.asyncmvp.http.AsyncCachedHttpRequest.java

private void makeRequest() throws IOException {
    HttpResponse response = client.execute(request, context);

    StatusLine status = response.getStatusLine();
    if (status.getStatusCode() >= 300) {
        responseHandler.onFailure(protocol,
                new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
    } else {//www  . j av a2  s. c o m
        byte[] httpResponseByte = EntityUtils.toByteArray(response.getEntity());
        // add to cache
        ResponseData responseData = new ResponseData(status.getStatusCode(), httpResponseByte);
        try {
            AsyncCacheClient.getInstance().put(cacheProtocol, cacheId, responseData);
        } catch (NullPointerException e) {
            // no cache
        }
        responseHandler.onSuccess(protocol, httpResponseByte);
    }
}

From source file:com.uzmap.pkg.uzmodules.uzBMap.methods.MapGoogleCoords.java

private JSONObject getRespJson(HttpEntity httpEntity) {
    try {/*  w w w. j  av a2  s .  co  m*/
        String str = new String(EntityUtils.toByteArray(httpEntity), getCharSet(httpEntity));
        JSONObject json = new JSONObject(str);
        return json;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}