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.sailthru.android.sdk.impl.external.retrofit.client.ApacheClient.java

static Response parseResponse(String url, HttpResponse response) throws IOException {
    StatusLine statusLine = response.getStatusLine();
    int status = statusLine.getStatusCode();
    String reason = statusLine.getReasonPhrase();

    List<Header> headers = new ArrayList<Header>();
    String contentType = "application/octet-stream";
    for (org.apache.http.Header header : response.getAllHeaders()) {
        String name = header.getName();
        String value = header.getValue();
        if ("Content-Type".equalsIgnoreCase(name)) {
            contentType = value;/*  w w w  .  j  a  va  2 s.  com*/
        }
        headers.add(new Header(name, value));
    }

    TypedByteArray body = null;
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        byte[] bytes = EntityUtils.toByteArray(entity);
        body = new TypedByteArray(contentType, bytes);
    }

    return new Response(url, status, reason, headers, body);
}

From source file:org.jssec.android.https.imagesearch.HttpImageSearch.java

@Override
protected Object doInBackground(String... params) {

    // HttpClient2?GET????????finally?shutdown?
    DefaultHttpClient client = new DefaultHttpClient();

    try {/*from  www .ja  v  a 2 s .  c o m*/
        // --------------------------------------------------------
        // 1??
        // --------------------------------------------------------

        // ?1 ???????
        // ???
        String search_url = Uri.parse("http://ajax.googleapis.com/ajax/services/search/images?v=1.0")
                .buildUpon().appendQueryParameter("q", params[0]).build().toString();
        HttpGet request = new HttpGet(search_url);
        HttpResponse response = client.execute(request);
        checkResponse(response);

        // ?2 ?????????
        // ??????????????
        // ????JSON???
        String result_json = EntityUtils.toString(response.getEntity(), "UTF-8");
        String image_url = new JSONObject(result_json).getJSONObject("responseData").getJSONArray("results")
                .getJSONObject(0).getString("url");

        // --------------------------------------------------------
        // 2???
        // --------------------------------------------------------

        // ?1 ???????
        request = new HttpGet(image_url);
        response = client.execute(request);
        checkResponse(response);

        // ?2 ?????????
        return EntityUtils.toByteArray(response.getEntity());
    } catch (Exception e) {
        return e;
    } finally {
        // ?HttpClientshutdown?
        client.getConnectionManager().shutdown();
    }
}

From source file:it.polito.tellmefirst.classify.threads.GetWikiHtmlThread.java

@Override
public void run() {

    LOG.debug("[run] - BEGIN");
    LOG.debug("Thread " + this.getId() + " started.");
    long startTime = System.currentTimeMillis();

    HttpEntity entity = null;//from  ww w. j a  v a2s . c  o  m
    CloseableHttpResponse response = null;
    String wikihtml = null;
    String[] temp = null;
    JSONObject jsonObject = null;

    try {

        LOG.debug("Executing httpget = " + httpget.getURI());
        response = httpClient.execute(httpget, context);
        LOG.debug("Thread " + this.getId() + " get executed.");
        try {
            entity = response.getEntity();
            byte[] bytes = null;
            String resp = null;

            if (entity != null) {
                bytes = EntityUtils.toByteArray(entity);
                LOG.debug(" - " + bytes.length + " bytes read");
                resp = new String(bytes);
                jsonObject = new JSONObject(resp);
                wikihtml = (String) jsonObject.getJSONObject("parse").getJSONObject("text").get("*");

                synchronized (result) {
                    temp = result.get(index);
                    temp[7] = wikihtml;
                    result.set(index, temp);
                }

            }

        } catch (JSONException e) {
            LOG.error("[run] - EXCEPTION: ", e);
        } catch (Exception e) {
            LOG.error("[run] - EXCEPTION: ", e);
        } finally {
            response.close();
        }
    } catch (ClientProtocolException ex) {
        // Handle protocol errors
        LOG.error("[run] - EXCEPTION: ", ex);
    } catch (IOException ex) {
        // Handle I/O errors
        LOG.error("[run] - EXCEPTION: ", ex);
    }

    long endTime = System.currentTimeMillis();
    long duration = (endTime - startTime) / 1000;

    LOG.debug("Thread " + this.getId() + " finished and took " + duration + " seconds. ###########");
    LOG.debug("[run] - END");
}

From source file:org.eclipse.jetty.rhttp.client.ApacheClient.java

protected void asyncConnect() {
    new Thread() {
        @Override//from w ww . ja v a2 s  . co  m
        public void run() {
            try {
                HttpPost connect = new HttpPost(gatewayPath + "/" + urlEncode(getTargetId()) + "/connect");
                getLogger().debug("Client {} connect sent to gateway", getTargetId(), null);
                HttpResponse response = httpClient.execute(connect);
                int statusCode = response.getStatusLine().getStatusCode();
                HttpEntity entity = response.getEntity();
                byte[] responseContent = EntityUtils.toByteArray(entity);
                if (statusCode == HttpStatus.SC_OK)
                    connectComplete(responseContent);
                else if (statusCode == HttpStatus.SC_UNAUTHORIZED)
                    notifyConnectRequired();
                else
                    notifyConnectException();
            } catch (NoHttpResponseException x) {
                notifyConnectClosed();
            } catch (IOException x) {
                getLogger().debug("", x);
                notifyConnectException();
            }
        }
    }.start();
}

From source file:com.bazaarvoice.test.SubmissionTests.VideoSubmissionTest.java

public void testVideoSubmit() {

    //Your PC can't communicate with your device and access your sd card at the same time.  So for this test, lets
    //download a well know video that we don't think is going anywhere so the tests will successfully complete.  If
    //this fails just change the url to something that works
    byte[] imageBytes = null;
    try {/*w w w . ja v  a  2 s  .  c  o m*/
        HttpRequestBase httpRequest = new HttpGet(
                "http://glass.googlecode.com/svn-history/r151/trunk/intro.avi");
        HttpClient httpClient = new DefaultHttpClient();

        HttpResponse response = httpClient.execute(httpRequest);
        StatusLine statusLine = response.getStatusLine();
        int status = statusLine.getStatusCode();

        if (status < 200 || status > 299) {
            throw new BazaarException(
                    "Error communicating with server. " + statusLine.getReasonPhrase() + " " + status);
        } else {
            HttpEntity entity = response.getEntity();
            imageBytes = EntityUtils.toByteArray(entity);
        }
    } catch (Exception e) {
        throw new RuntimeException("Error getting a video for a test!\n");
    }

    OnBazaarResponseHelper bazaarResponse = new OnBazaarResponseHelper() {
        @Override
        public void onResponseHelper(JSONObject response) throws JSONException {
            Log.e(tag, "End of video submit transmission : END " + System.currentTimeMillis());

            Log.i(tag, "Response = \n" + response);

            assertFalse("The test returned errors! ", response.getBoolean("HasErrors"));
            assertNotNull(response.getJSONObject("Video").getString("VideoUrl"));
        }
    };

    SubmissionMediaParams mediaParams = new SubmissionMediaParams(MediaParamsContentType.REVIEW);
    mediaParams.setUserId(
            "735688f97b74996e214f5df79bff9e8b7573657269643d393274796630666f793026646174653d3230313130353234");
    try {

        mediaParams.setVideo(imageBytes, "Android_Video.mp4");

        Log.e(tag, "Begin of video submit transmission : BEGIN " + System.currentTimeMillis());
        submitMedia.postSubmission(RequestType.VIDEOS, mediaParams, bazaarResponse);

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    bazaarResponse.waitForTestToFinish();
}

From source file:net.potterpcs.recipebook.DownloadImageTask.java

private Bitmap downloadImage(String... urls) {
    Bitmap bitmap = null;//from   ww  w . j a  v a2 s . c  om
    RecipeData data = ((RecipeBook) parent.getApplication()).getData();

    AndroidHttpClient client = AndroidHttpClient.newInstance("A to Z Recipes for Android");

    if (data.isCached(urls[0])) {
        // Retrieve a cached image if we have one
        String pathName = data.findCacheEntry(urls[0]);
        Uri pathUri = Uri.fromFile(new File(parent.getCacheDir(), pathName));
        try {
            bitmap = RecipeBook.decodeScaledBitmap(parent, pathUri);
        } catch (IOException e) {
            e.printStackTrace();
            bitmap = null;
        }
    } else {
        try {
            // If the image isn't in the cache, we have to go and get it.
            // First, we set up the HTTP request.
            HttpGet request = new HttpGet(urls[0]);
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setSoTimeout(params, 60000);
            request.setParams(params);

            // Let the UI know we're working.
            publishProgress(25);

            // Retrieve the image from the network.
            HttpResponse response = client.execute(request);
            publishProgress(50);

            // Create a bitmap to put in the ImageView.
            byte[] image = EntityUtils.toByteArray(response.getEntity());
            bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
            publishProgress(75);

            // Cache the file for offline use, and to lower data usage.
            File cachePath = parent.getCacheDir();
            String cacheFile = "recipecache-" + Long.toString(System.currentTimeMillis());
            if (bitmap.compress(Bitmap.CompressFormat.PNG, 0,
                    new FileOutputStream(new File(cachePath, cacheFile)))) {
                RecipeData appData = ((RecipeBook) parent.getApplication()).getData();
                appData.insertCacheEntry(urls[0], cacheFile);
            }
            //            Log.v(TAG, cacheFile);

            // We're done!
            publishProgress(100);
        } catch (IOException e) {
            // TODO Maybe a dialog?
        }

    }
    client.close();
    return bitmap;
}

From source file:org.jssec.android.https.imagesearch.HttpsImageSearch.java

@Override
protected Object doInBackground(String... params) {

    // HttpClient2?GET????????finally?shutdown?
    DefaultHttpClient client = new DefaultHttpClient();

    try {//from   w ww .  j  a  v  a 2  s.c  om
        // --------------------------------------------------------
        // 1??
        // --------------------------------------------------------

        // ?1 URI?https://??
        // ?2 ???????
        String search_url = Uri.parse("https://ajax.googleapis.com/ajax/services/search/images?v=1.0")
                .buildUpon().appendQueryParameter("q", params[0]).build().toString();
        HttpGet request = new HttpGet(search_url);
        HttpResponse response = client.execute(request);
        checkResponse(response);

        // ?3 HTTPS??????????????
        // ????3.2 ?????
        String result_json = EntityUtils.toString(response.getEntity(), "UTF-8");
        String image_url = new JSONObject(result_json).getJSONObject("responseData").getJSONArray("results")
                .getJSONObject(0).getString("url");

        // --------------------------------------------------------
        // 2???
        // --------------------------------------------------------

        // ?1 URI?https://??
        // ?2 ???????
        request = new HttpGet(image_url);
        response = client.execute(request);
        checkResponse(response);

        // ?3 HTTPS??????????????
        // ????3.2 ?????
        return EntityUtils.toByteArray(response.getEntity());
    } catch (SSLException e) {
        // ?4 SSLException?????????
        // ??????
        return e;
    } catch (Exception e) {
        return e;
    } finally {
        // ?HttpClientshutdown?
        client.getConnectionManager().shutdown();
    }
}

From source file:org.red5.client.net.rtmps.RTMPTSClientConnector.java

@Override
public void run() {
    HttpPost post = null;// w  w  w .  j a v  a2s.co  m
    try {
        RTMPTClientConnection conn = openConnection();
        // set a reference to the connection on the client
        client.setConnection((RTMPConnection) conn);
        // set thread local
        Red5.setConnectionLocal(conn);
        while (!conn.isClosing() && !stopRequested) {
            IoBuffer toSend = conn.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);
                post.addHeader("Content-Type", CONTENT_TYPE);
            }
            // execute
            HttpResponse response = httpClient.execute(targetHost, post);
            // check for error
            checkResponseCode(response);
            // handle data
            byte[] received = EntityUtils.toByteArray(response.getEntity());
            // wrap the bytes
            IoBuffer data = IoBuffer.wrap(received);
            log.debug("State: {}", RTMP.states[conn.getStateCode()]);
            // ensure handshake is done
            if (conn.hasAttribute(RTMPConnection.RTMP_HANDSHAKE)) {
                client.messageReceived(data);
                continue;
            }
            if (data.limit() > 0) {
                data.skip(1); // XXX: polling interval lies in this byte
            }
            List<?> messages = conn.decode(data);
            if (messages == null || messages.isEmpty()) {
                try {
                    // XXX handle polling delay
                    Thread.sleep(250);
                } catch (InterruptedException e) {
                    if (stopRequested) {
                        post.abort();
                        break;
                    }
                }
                continue;
            }
            for (Object message : messages) {
                try {
                    client.messageReceived(message);
                } catch (Exception e) {
                    log.error("Could not process message", e);
                }
            }
        }
        finalizeConnection();
        client.connectionClosed(conn);
    } catch (Throwable e) {
        log.debug("RTMPT handling exception", e);
        client.handleException(e);
        if (post != null) {
            post.abort();
        }
    } finally {
        Red5.setConnectionLocal(null);
    }
}

From source file:org.keycloak.authorization.client.util.HttpMethod.java

public R execute(HttpResponseProcessor<R> responseProcessor) {
    byte[] bytes = null;

    try {/*from  ww  w  .j  av  a  2 s  .  c  o m*/
        for (Map.Entry<String, String> header : this.headers.entrySet()) {
            this.builder.setHeader(header.getKey(), header.getValue());
        }

        preExecute(this.builder);

        HttpResponse response = this.httpClient.execute(this.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);
        }

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

        return responseProcessor.process(bytes);
    } catch (HttpResponseException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(
                "Error executing http method [" + builder + "]. Response : " + String.valueOf(bytes), e);
    }
}