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:lyrics.crawler.webClient.ContentDownloader.java

public byte[] getBinaryData(HttpHost targetHost, String content) throws DownloadException, IOException {
    HttpEntity entity = getContent(targetHost, content);
    return EntityUtils.toByteArray(entity);
}

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

public void testPhotoSubmit() {

    //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 image 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 {/*from  w  w w .  j a  v  a2 s .  com*/
        HttpRequestBase httpRequest = new HttpGet(
                "http://fc04.deviantart.net/images/i/2002/26/9/1/Misconstrue_-_Image_1.jpg");
        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 an image for a test!\n");
    }

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

            Log.i(tag, "Response = \n" + response);
            assertFalse("The test returned errors! ", response.getBoolean("HasErrors"));
            assertNotNull(response.getJSONObject("Photo"));
        }
    };

    SubmissionMediaParams mediaParams = new SubmissionMediaParams(MediaParamsContentType.REVIEW_COMMENT);
    mediaParams.setUserId(
            "735688f97b74996e214f5df79bff9e8b7573657269643d393274796630666f793026646174653d3230313130353234");
    try {
        mediaParams.setPhoto(imageBytes, "Misconstrue_-_Image_1.jpg");

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

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

From source file:base.tina.external.http.HttpTask.java

@Override
public final void run() throws Exception {
    if (httpPlugin == null || httpPlugin.url == null)
        return;//from  w  ww . j  ava  2 s . com
    //#debug 
    base.tina.core.log.LogPrinter.d(null, "-----------" + httpPlugin.url + "-----------");
    httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
    HttpResponse response;

    if (httpPlugin.requestData == null && httpPlugin.requestDataInputStream == null) {
        HttpGet getRequest = new HttpGet(URI.create(httpPlugin.url));
        request = getRequest;
        response = httpClient.execute(getRequest);
    } else {
        HttpPost requestPost = new HttpPost(URI.create(httpPlugin.url));

        request = requestPost;

        // request.setHeader("Connention", "close");

        if (httpPlugin.requestDataInputStream != null) {
            InputStream instream = httpPlugin.requestDataInputStream;
            InputStreamEntity inputStreamEntity = new InputStreamEntity(instream, httpPlugin.dataLength);
            requestPost.setEntity(inputStreamEntity);
        } else {
            InputStream instream = new ByteArrayInputStream(httpPlugin.requestData);
            InputStreamEntity inputStreamEntity = new InputStreamEntity(instream,
                    httpPlugin.requestData.length);
            requestPost.setEntity(inputStreamEntity);
        }
        response = httpClient.execute(requestPost);
    }
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        httpPlugin.parseData(EntityUtils.toByteArray(response.getEntity()));
        commitResult(httpPlugin, CommitAction.WAKE_UP);
    } else {
        //#debug error
        base.tina.core.log.LogPrinter.e(null,
                "Http error : " + new String(EntityUtils.toByteArray(response.getEntity())));
        throw new Exception("Http response code is : " + response.getStatusLine().getStatusCode());
    }
}

From source file:net.sarangnamu.common.network.BkHttp.java

public byte[] bytesSubmit(String getUrl, final Map<String, String> parameters) throws Exception {
    HttpEntity entity = null;/*from w w w.  j  a va 2 s .co  m*/

    if (method.equals("GET")) {
        entity = methodGet(getUrl, parameters);
    } else {
        entity = methodPost(getUrl, parameters);
    }

    return EntityUtils.toByteArray(entity);
}

From source file:jp.ambrosoli.quickrestclient.apache.response.ApacheHttpResponse.java

/**
 * {@link HttpEntity}?byte???????//from  w  ww. j a v a2s  .co m
 * 
 * @param entity
 *            HTTP
 * @return ???byte?
 */
public byte[] toByteArray(final HttpEntity entity) {
    if (entity == null) {
        return null;
    }

    try {
        return EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        throw new IORuntimeException();
    }
}

From source file:org.zalando.stups.tokens.CloseableTokenVerifier.java

@Override
public boolean isTokenValid(String token) {

    final HttpGet request = new HttpGet(tokenInfoUri);
    request.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
    request.setHeader(AUTHORIZATION, "Bearer " + token);
    request.setConfig(requestConfig);/*from   ww  w. j a  va2 s  .c  o  m*/

    long start = System.currentTimeMillis();
    boolean success = true;
    try (final CloseableHttpResponse response = client.execute(host, request)) {

        // success status code?
        final int status = response.getStatusLine().getStatusCode();
        if (status < 400) {
            // seems to be ok
            return true;
        } else if (status >= 400 && status < 500) {
            // get json response
            final HttpEntity entity = response.getEntity();
            final ProblemResponse problemResponse = objectMapper.readValue(EntityUtils.toByteArray(entity),
                    ProblemResponse.class);
            // do we want to do something with problem?
            // seems to be invalid
            return false;
        }

    } catch (Throwable t) {
        // how to handle this? For now, do not delete the token
        success = false;
        return true;
    } finally {
        long time = System.currentTimeMillis() - start;
        metricsListener.submitToTimer(Metrics.buildMetricsKey(METRICS_KEY_PREFIX, success), time);
    }
    return true;
}

From source file:com.traffic.common.utils.http.HttpClientUtils.java

/**
 * ,result""//from  w  ww . ja v  a2 s.co  m
 * 
 * @param url
 * @param param
 * @return
 */
public static String httpPost(String url, String paramvalue) {
    logger.info("httpPost URL [" + url + "] start ");
    if (logger.isDebugEnabled()) {
        logger.debug("httpPost body :" + paramvalue);
    }
    logger.info("httpPost body :" + paramvalue);
    HttpClient httpclient = null;
    HttpPost httpPost = null;
    HttpResponse response = null;
    HttpEntity entity = null;
    String result = "";

    try {
        httpclient = HttpConnectionManager.getHttpClient();
        // cookie---??
        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        httpPost = new HttpPost(url);
        // ???
        for (Entry<String, String> entry : headers.entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }

        StringEntity stringEntity = new StringEntity(paramvalue, "UTF-8");
        httpPost.setEntity(stringEntity);

        // 
        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 40000);
        // ?
        HttpConnectionParams.setSoTimeout(httpPost.getParams(), 200000);
        response = httpclient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("HttpStatus ERROR" + "Method failed: " + response.getStatusLine());
            return "";
        } else {
            entity = response.getEntity();
            if (null != entity) {
                byte[] bytes = EntityUtils.toByteArray(entity);
                result = new String(bytes, "UTF-8");
            } else {
                logger.error("httpPost URL [" + url + "],httpEntity is null.");
            }
            return result;
        }
    } catch (Exception e) {
        logger.error("httpPost URL [" + url + "] error, ", e);
        return "";
    }
}

From source file:io.github.theguy191919.udpft.net.TCPSenderReceiver.java

@Override
public void run() {
    int sleepFor = 100;
    while (this.running) {
        sleepFor += 10;//  ww  w . j  a v a 2  s. c o  m
        while (!this.que.isEmpty()) {
            sleepFor -= 50;
            SentContent thing = this.que.poll();
            if (thing == null) {
                break;
            }
            byte[] bytearray = thing.getMessage();
            String url = thing.getUrl();
            this.crypto.encrypt(bytearray);

            //this.printArray("Sending message", bytearray, "End of message");

            HttpPost post = new HttpPost(url);
            //List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            //nvps.add(new BasicNameValuePair("data", ));
            post.setEntity(new ByteArrayEntity(bytearray));
            try {
                HttpResponse response = client.execute(post);
                byte[] reply = EntityUtils.toByteArray(response.getEntity());
                this.messageGotten(reply);
            } catch (IOException ex) {
                Logger.getLogger(TCPSenderReceiver.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (sleepFor < 0) {
            sleepFor = 0;
        } else if (sleepFor > 500) {
            sleepFor = 1000;
        }
        try {
            Thread.sleep(sleepFor);
        } catch (InterruptedException ex) {
            Logger.getLogger(Sender.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.meltmedia.cadmium.blackbox.test.CadmiumAssertions.java

/**
 * <p>Asserts that the local and remote files pass to this method exist and are identical.</p>
 * @param message The message that will be in the error if the local file isn't the same as the remote file.
 * @param toCheck The file to check/* w ww .java 2  s. c o m*/
 * @param username The Basic HTTP auth username.
 * @param password The Basic HTTP auth password.
 * @param remoteLocation A string containing the URL location of the remote resource to check.
 */
public static void assertResourcesEqual(String message, File toCheck, String remoteLocation, String username,
        String password) {
    FileReader reader = null;
    assertExistsLocally(message, toCheck);
    try {
        reader = new FileReader(toCheck);
        byte fileContents[] = IOUtils.toByteArray(reader);
        byte remoteContents[] = EntityUtils
                .toByteArray(assertExistsRemotely(message, remoteLocation, username, password));
        if (!Arrays.equals(fileContents, remoteContents)) {
            throw new AssertionFailedError(message);
        }
    } catch (IOException e) {
        throw new AssertionFailedError(e.getMessage() + ": " + message);
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:com.geekandroid.sdk.pay.utils.Util.java

public static byte[] httpPost(String url, String entity) {
    if (url == null || url.length() == 0) {
        Log.e(TAG, "httpPost, url is null");
        return null;
    }/*from  w  w w  . j  av a  2  s .  co m*/

    HttpClient httpClient = getNewHttpClient();

    HttpPost httpPost = new HttpPost(url);

    try {
        httpPost.setEntity(new StringEntity(entity));
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        HttpResponse resp = httpClient.execute(httpPost);
        if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            Log.e(TAG, "httpGet fail, status code = " + resp.getStatusLine().getStatusCode());
            return null;
        }

        return EntityUtils.toByteArray(resp.getEntity());
    } catch (Exception e) {
        Log.e(TAG, "httpPost exception, e = " + e.getMessage());
        e.printStackTrace();
        return null;
    }
}