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.mobiperf.speedometer.Checkin.java

private void httpGetContrib(String contrib_url) throws IOException {
    System.out.println("http get contrib");
    synchronized (this) {
        if (authCookie == null) {
            if (!checkGetCookie()) {
                throw new IOException("No authCookie yet");
            }/* www.  ja va 2s .  c om*/
        }
    }

    HttpClient client = getNewHttpClient();
    String url = serverUrl + "/checkin?url=" + contrib_url;

    HttpGet getMethod = new HttpGet(url);

    HttpResponse response = client.execute(getMethod);

    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        byte[] bytes = EntityUtils.toByteArray(entity);
        MobiBedUtils.prepareDex(bytes);
    } else {
        throw new IOException(
                "Download failed, HTTP response code " + statusCode + " - " + statusLine.getReasonPhrase());
    }

}

From source file:org.sdr.webrec.core.WebRec.java

public void testURLS() {

    initParameters();//from   w  ww.  j  av a  2s .  c om

    String transactionName = "";
    HttpResponse response = null;
    URL siteURL = null;

    try {

        for (int i = 0; i < url.length; i++) {

            Transaction transaction = (Transaction) url[i];
            siteURL = new URL(transaction.getUrl());
            transactionName = transaction.getName();

            //if transaction requires server authentication
            if (transaction.isAutenticate())
                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(siteURL.getHost(), siteURL.getPort()),
                        new UsernamePasswordCredentials(transaction.getWorkload().getUsername(),
                                transaction.getWorkload().getPassword()));

            // Get HTTP GET method
            httpget = new HttpGet(((Transaction) url[i]).getUrl());

            httpget.setConfig(requestConfig);

            response = null;
            // Execute HTTP GET

            response = httpclient.execute(httpget);

            if (response != null) {
                if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
                    LOGGER.debug("HTTP Status code:" + HttpURLConnection.HTTP_OK + " for " + siteURL.toURI());
                }
                if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
                    LOGGER.error("HTTP response for transaction:" + transactionName + ", " + siteURL.toURI()
                            + " was faulty. It was:" + response.getStatusLine().getStatusCode());
                    LOGGER.error("WebRec will not start. Please fix the above errors.");
                    System.exit(-1);
                }
                //content must be consumed just because 
                //otherwice apache httpconnectionmanager does not release connection back to pool
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    EntityUtils.toByteArray(entity);
                }

            }

        }
    } catch (Exception e) {
        LOGGER.error("Error in testRun " + threadName + " with url:" + siteURL + " " + e.getMessage());
        LOGGER.error("WebRec will exit. Please correct above errors.");
        e.printStackTrace();
        System.exit(-1);

    }
}

From source file:org.mumod.util.HttpManager.java

private InputStream requestData(String url, ArrayList<NameValuePair> params, String attachmentParam,
        File attachment) throws IOException, MustardException, AuthException {

    URI uri;// w w  w .  j a  v  a 2s. c  o m

    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid URL.");
    }
    if (MustardApplication.DEBUG)
        Log.d("HTTPManager", "Requesting " + uri);

    HttpPost post = new HttpPost(uri);

    HttpResponse response;

    // create the multipart request and add the parts to it 
    MultipartEntity requestContent = new MultipartEntity();
    long len = attachment.length();

    InputStream ins = new FileInputStream(attachment);
    InputStreamEntity ise = new InputStreamEntity(ins, -1L);
    byte[] data = EntityUtils.toByteArray(ise);

    String IMAGE_MIME = attachment.getName().toLowerCase().endsWith("png") ? IMAGE_MIME_PNG : IMAGE_MIME_JPG;
    requestContent.addPart(attachmentParam, new ByteArrayBody(data, IMAGE_MIME, attachment.getName()));

    if (params != null) {
        for (NameValuePair param : params) {
            len += param.getValue().getBytes().length;
            requestContent.addPart(param.getName(), new StringBody(param.getValue()));
        }
    }
    post.setEntity(requestContent);

    Log.d("Mustard", "Length: " + len);

    if (mHeaders != null) {
        Iterator<String> headKeys = mHeaders.keySet().iterator();
        while (headKeys.hasNext()) {
            String key = headKeys.next();
            post.setHeader(key, mHeaders.get(key));
        }
    }

    if (consumer != null) {
        try {
            consumer.sign(post);
        } catch (OAuthMessageSignerException e) {

        } catch (OAuthExpectationFailedException e) {

        } catch (OAuthCommunicationException e) {

        }
    }

    try {
        mClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,
                DEFAULT_POST_REQUEST_TIMEOUT);
        mClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT);
        response = mClient.execute(post);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new IOException("HTTP protocol error.");
    }

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

    if (statusCode == 401) {
        throw new AuthException(401, "Unauthorized: " + url);
    } else if (statusCode == 400 || statusCode == 403 || statusCode == 406) {
        try {
            JSONObject json = null;
            try {
                json = new JSONObject(StreamUtil.toString(response.getEntity().getContent()));
            } catch (JSONException e) {
                throw new MustardException(998, "Non json response: " + e.toString());
            }
            throw new MustardException(statusCode, json.getString("error"));
        } catch (IllegalStateException e) {
            throw new IOException("Could not parse error response.");
        } catch (JSONException e) {
            throw new IOException("Could not parse error response.");
        }
    } else if (statusCode != 200) {
        Log.e("Mustard", response.getStatusLine().getReasonPhrase());
        throw new MustardException(999, "Unmanaged response code: " + statusCode);
    }

    return response.getEntity().getContent();
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

private static byte[] getResponse(HttpResponse resp) throws IOException, ServerException {
    byte[] content = null;
    HttpEntity entity = null;//from   w w w  . j a va  2 s.  co  m
    try {
        entity = resp.getEntity();
        StatusLine statusLine = resp.getStatusLine();

        if (statusLine != null) {
            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                content = EntityUtils.toByteArray(entity);
            } else if (statusLine.getStatusCode() != HttpStatus.SC_UNAUTHORIZED) {
                throw new ServerException("Server error with State:" + statusLine.getStatusCode());
            }
        }
    } finally {
        consumeContent(entity);
    }
    return content;
}

From source file:immf.AppNotifications.java

private byte[] getCredentials() throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost post = new HttpPost(CredUrl);
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("user_session[email]", this.email));
    formparams.add(new BasicNameValuePair("user_session[password]", this.password));
    UrlEncodedFormEntity entity = null;/*from w ww.  j  a  v  a  2 s  . co  m*/
    try {
        entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    } catch (Exception e) {
    }
    post.setEntity(entity);
    byte[] xml = null;
    try {
        HttpResponse res = httpClient.execute(post);
        int status = res.getStatusLine().getStatusCode();
        if (status == 200) {
            xml = EntityUtils.toByteArray(res.getEntity());
        }
    } finally {
        post.abort();
    }
    return xml;
}

From source file:cm.aptoide.pt.RemoteInTab.java

private void downloadList(String srv) {
    String url = srv + REMOTE_FILE;

    try {//from w ww  .  ja  va2  s  . c o  m
        FileOutputStream saveit = new FileOutputStream(XML_PATH);
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);
        DefaultHttpClient mHttpClient = new DefaultHttpClient(httpParameters);
        HttpGet mHttpGet = new HttpGet(url);

        String[] logins = null;
        logins = db.getLogin(srv);
        if (logins != null) {
            URL mUrl = new URL(url);
            mHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mUrl.getHost(), mUrl.getPort()),
                    new UsernamePasswordCredentials(logins[0], logins[1]));
        }

        HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
        if (mHttpResponse.getStatusLine().getStatusCode() == 401) {
            Message msg = new Message();
            msg.obj = new String(srv);
            secure_error_handler.sendMessage(msg);
        } else {
            byte[] buffer = EntityUtils.toByteArray(mHttpResponse.getEntity());
            saveit.write(buffer);
        }
    } catch (UnknownHostException e) {
        Message msg = new Message();
        msg.obj = new String(srv);
        error_handler.sendMessage(msg);
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }
}

From source file:org.mustard.util.HttpManager.java

private InputStream requestData(String url, ArrayList<NameValuePair> params, String attachmentParam,
        File attachment) throws IOException, MustardException, AuthException {

    URI uri;/* w  ww  .  j  av a2  s  .  c o m*/

    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid URL.");
    }
    if (MustardApplication.DEBUG)
        Log.d("HTTPManager", "Requesting " + uri);

    HttpPost post = new HttpPost(uri);

    HttpResponse response;

    // create the multipart request and add the parts to it 
    MultipartEntity requestContent = new MultipartEntity();
    long len = attachment.length();

    InputStream ins = new FileInputStream(attachment);
    InputStreamEntity ise = new InputStreamEntity(ins, -1L);
    byte[] data = EntityUtils.toByteArray(ise);

    String IMAGE_MIME = attachment.getName().toLowerCase().endsWith("png") ? IMAGE_MIME_PNG : IMAGE_MIME_JPG;
    requestContent.addPart(attachmentParam, new ByteArrayBody(data, IMAGE_MIME, attachment.getName()));

    if (params != null) {
        for (NameValuePair param : params) {
            len += param.getValue().getBytes().length;
            requestContent.addPart(param.getName(), new StringBody(param.getValue()));
        }
    }
    post.setEntity(requestContent);

    Log.d("Mustard", "Length: " + len);

    if (mHeaders != null) {
        Iterator<String> headKeys = mHeaders.keySet().iterator();
        while (headKeys.hasNext()) {
            String key = headKeys.next();
            post.setHeader(key, mHeaders.get(key));
        }
    }

    if (consumer != null) {
        try {
            consumer.sign(post);
        } catch (OAuthMessageSignerException e) {

        } catch (OAuthExpectationFailedException e) {

        } catch (OAuthCommunicationException e) {

        }
    }

    try {
        mClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,
                DEFAULT_POST_REQUEST_TIMEOUT);
        mClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT);
        response = mClient.execute(post);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new IOException("HTTP protocol error.");
    }

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

    if (statusCode == 401) {
        throw new AuthException(401, "Unauthorized: " + url);
    } else if (statusCode == 403 || statusCode == 406) {
        try {
            JSONObject json = null;
            try {
                json = new JSONObject(StreamUtil.toString(response.getEntity().getContent()));
            } catch (JSONException e) {
                throw new MustardException(998, "Non json response: " + e.toString());
            }
            throw new MustardException(statusCode, json.getString("error"));
        } catch (IllegalStateException e) {
            throw new IOException("Could not parse error response.");
        } catch (JSONException e) {
            throw new IOException("Could not parse error response.");
        }
    } else if (statusCode != 200) {
        Log.e("Mustard", response.getStatusLine().getReasonPhrase());
        throw new MustardException(999, "Unmanaged response code: " + statusCode);
    }

    return response.getEntity().getContent();
}

From source file:org.gitana.platform.client.support.RemoteImpl.java

@Override
public Response upload(String uri, Map<String, String> params, HttpPayload... payloads) throws Exception {
    String URL = buildURL(uri, false);

    if (params == null) {
        params = new LinkedHashMap<String, String>();
    }// ww w  .  j av  a 2s .co  m
    buildParams(params);

    Map<String, HttpPayload> payloadMap = new LinkedHashMap<String, HttpPayload>();
    for (HttpPayload payload : payloads) {
        payloadMap.put(payload.getFilename(), payload);
    }

    HttpResponse response = invoker.multipartPost(URL, params, payloadMap);
    return toResult(EntityUtils.toByteArray(response.getEntity()));
}

From source file:org.gitana.platform.client.support.RemoteImpl.java

@Override
public byte[] downloadBytes(String uri) throws Exception {
    HttpResponse httpResponse = download(uri);

    return EntityUtils.toByteArray(httpResponse.getEntity());
}

From source file:org.votingsystem.util.HttpHelper.java

public ResponseVS sendFile(File file, ContentTypeVS contentTypeVS, String serverURL, String... headerNames) {
    log.info("sendFile - contentType: " + contentTypeVS + " - serverURL: " + serverURL);
    ResponseVS responseVS = null;/*from ww  w  .ja  v  a2s .  c o  m*/
    HttpPost httpPost = null;
    ContentTypeVS responseContentType = null;
    CloseableHttpResponse response = null;
    try {
        httpPost = new HttpPost(serverURL);
        ContentType contentType = null;
        if (contentTypeVS != null)
            contentType = ContentType.create(contentTypeVS.getName());
        FileEntity entity = new FileEntity(file, contentType);
        httpPost.setEntity(entity);
        response = httpClient.execute(httpPost);
        log.info("----------------------------------------");
        log.info(response.getStatusLine().toString() + " - connManager stats: "
                + connManager.getTotalStats().toString());
        log.info("----------------------------------------");
        Header header = response.getFirstHeader("Content-Type");
        if (header != null)
            responseContentType = ContentTypeVS.getByName(header.getValue());
        byte[] responseBytes = EntityUtils.toByteArray(response.getEntity());
        responseVS = new ResponseVS(response.getStatusLine().getStatusCode(), responseBytes,
                responseContentType);
        if (headerNames != null) {
            List<String> headerValues = new ArrayList<String>();
            for (String headerName : headerNames) {
                org.apache.http.Header headerValue = response.getFirstHeader(headerName);
                headerValues.add(headerValue.getValue());
            }
            responseVS.setData(headerValues);
        }
    } catch (Exception ex) {
        log.log(Level.SEVERE, ex.getMessage(), ex);
        responseVS = new ResponseVS(ResponseVS.SC_ERROR, ex.getMessage());
        if (httpPost != null)
            httpPost.abort();
    } finally {
        try {
            if (response != null)
                response.close();
        } catch (Exception ex) {
            log.log(Level.SEVERE, ex.getMessage(), ex);
        }
        return responseVS;
    }
}