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.allblacks.utils.web.HttpUtil.java

/**
 * Gets data from URL as byte[] throws {@link RuntimeException} If anything
 * goes wrong/*from   ww w  .  j a  v  a 2 s.c om*/
 * 
 * @return The content of the URL as a byte[]
 * @throws java.io.IOException
 */
public byte[] getDataAsByteArray(String url, CredentialsProvider cp) throws IOException {
    HttpClient httpClient = getNewHttpClient();

    URL urlObj = new URL(url);
    HttpHost host = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol());

    HttpContext credContext = new BasicHttpContext();
    credContext.setAttribute(ClientContext.CREDS_PROVIDER, cp);

    HttpGet job = new HttpGet(url);
    HttpResponse response = httpClient.execute(host, job, credContext);

    HttpEntity entity = response.getEntity();
    return EntityUtils.toByteArray(entity);
}

From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientImpl.java

public byte[] send(byte[] request) {
    while (true) {
        HttpClientContext context = HttpClientContext.create();

        context.setTargetHost(host);/*  w w w  . j av  a 2 s .co m*/

        // Set the credentials if they were provided.
        if (null != this.credentials) {
            context.setCredentialsProvider(credentialsProvider);
            context.setAuthSchemeRegistry(authRegistry);
            context.setAuthCache(authCache);
        }

        ByteArrayEntity entity = new ByteArrayEntity(request, ContentType.APPLICATION_OCTET_STREAM);

        // Create the client with the AuthSchemeRegistry and manager
        HttpPost post = new HttpPost(uri);
        post.setEntity(entity);

        try (CloseableHttpResponse response = execute(post, context)) {
            final int statusCode = response.getStatusLine().getStatusCode();
            if (HttpURLConnection.HTTP_OK == statusCode
                    || HttpURLConnection.HTTP_INTERNAL_ERROR == statusCode) {
                return EntityUtils.toByteArray(response.getEntity());
            } else if (HttpURLConnection.HTTP_UNAVAILABLE == statusCode) {
                LOG.debug("Failed to connect to server (HTTP/503), retrying");
                continue;
            }

            throw new RuntimeException("Failed to execute HTTP Request, got HTTP/" + statusCode);
        } catch (NoHttpResponseException e) {
            // This can happen when sitting behind a load balancer and a backend server dies
            LOG.debug("The server failed to issue an HTTP response, retrying");
            continue;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            LOG.debug("Failed to execute HTTP request", e);
            throw new RuntimeException(e);
        }
    }
}

From source file:com.orange.common.android.network.http.CustomBinaryHttpResponseHandler.java

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;
    //        }/*w ww .j  a va 2  s .co m*/
    //        Header contentTypeHeader = contentTypeHeaders[0];

    //        boolean foundAllowedContentType = false;
    //        for(String anAllowedContentType : mAllowedContentTypes) {
    //            if(anAllowedContentType.equals(contentTypeHeader.getValue())) {
    //                foundAllowedContentType = true;
    //            }
    //        }
    //        boolean foundAllowedContentType = true;   // disable this feature
    //        if(!foundAllowedContentType) {
    //            //Content-Type not in allowed list, ABORT!
    //            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);

        /*
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        InputStream inputStream = new BufferedInputStream(response.getEntity().getContent());
        int offset = -1;
        byte[] buffer = new byte[10240];
        while ((offset = inputStream.read(buffer, 0, 10240)) != -1) {                            
           output.write(buffer, 0, offset);
           output.flush();
                
           if (isStop){
         Log.d(TAG, "<http> detect stop flag, stop receive data");
         break;
           }
        }
                
        responseBody = output.toByteArray();
                
        output.close();
           inputStream.close();
                   
           if (isStop){
         return;
           }           
           */

    } catch (IOException e) {
        sendFailureMessage(e, (byte[]) null);
    } catch (Exception 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:ss.udapi.sdk.services.HttpServices.java

public ServiceRequest processLogin(ServiceRequest loginReq, String relation, String name) throws Exception {

    if (loginReq == null)
        throw new IllegalArgumentException("loginReq must be a valid request");

    logger.info("Preparing request for: " + name);
    CloseableHttpClient httpClient = HttpClients.custom().setKeepAliveStrategy(loginTimeout).build();
    List<RestItem> serviceRestItems = null;
    ServiceRequest serviceRequest = new ServiceRequest();

    RestItem loginDetails = getRestItems(loginReq, name);
    if (loginDetails == null) {
        logger.error("Link not found for request " + name);
        return null;
    }//  w ww  . j  av a 2s  .c  o m

    RestLink link = getLink(loginDetails, relation);
    if (link == null) {
        logger.error("Relation not found for relation: " + relation + " for " + name);
        return null;
    }

    CloseableHttpResponse response = null;
    try {

        HttpUriRequest httpAction = new HttpPost(link.getHref());
        if (compressionEnabled == true) {
            httpAction.setHeader("Accept-Encoding", "gzip");
        }

        httpAction.setHeader("X-Auth-User", SystemProperties.get("ss.username"));
        httpAction.setHeader("X-Auth-Key", SystemProperties.get("ss.password"));
        httpAction.setHeader("Content-Type", "application/json");

        // Send the request of to retrieve the Authentication Token and the
        // list of available services.
        response = httpClient.execute(httpAction);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new ClientProtocolException("Unexpected response status: "
                    + response.getStatusLine().getStatusCode() + " while retrieving services for: " + name);
        }

        if (response.getFirstHeader("X-Auth-Token") == null)
            throw new ClientProtocolException("Unexpected response: no auth token found");

        serviceAuthToken = response.getFirstHeader("X-Auth-Token").getValue();

        serviceRequest.setAuthToken(serviceAuthToken);
        HttpEntity entity = response.getEntity();
        String jsonResponse = new String(EntityUtils.toByteArray(entity));
        serviceRestItems = JsonHelper.toRestItems(jsonResponse);
        serviceRequest.setServiceRestItems(serviceRestItems);

        return serviceRequest;

    } catch (ClientProtocolException protEx) {
        logger.error(
                "Invalid Client Protocol: " + protEx.getMessage() + " while retrieving services for: " + name);
        throw protEx;
    } catch (IOException ioEx) {
        logger.error("Communication error" + ioEx.getCause() + " while retrieving services for: " + name);
        throw ioEx;
    } finally {
        try {
            httpClient.close();
        } catch (IOException ex) {
            // Can safely be ignored, either the server closed the
            // connection or we didn't open it so there's nothing to do
        }
    }
}

From source file:de.spqrinfo.cups4j.operations.IppOperation.java

/**
 * Sends a request to the provided url/*from   w w w  .  j a  va  2s. com*/
 *
 * @param url
 * @param ippBuf
 *
 * @param documentStream
 * @return result
 * @throws Exception
 */
private IppResult sendRequest(URL url, ByteBuffer ippBuf, InputStream documentStream) throws Exception {
    IppResult ippResult = null;
    if (ippBuf == null) {
        return null;
    }

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

    HttpClient 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", new Integer(10000));
    client.getParams().setParameter("http.connection.timeout", new Integer(10000));
    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 = new HttpPost(new URI("http://" + url.getHost() + ":" + ippPort) + url.getPath());

    httpPost.getParams().setParameter("http.socket.timeout", new Integer(10000));

    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);

    httpStatusLine = null;

    ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
        public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            HttpEntity entity = response.getEntity();
            httpStatusLine = response.getStatusLine().toString();
            if (entity != null) {
                return EntityUtils.toByteArray(entity);
            } else {
                return null;
            }
        }
    };

    byte[] result = client.execute(httpPost, handler);

    IppResponse ippResponse = new IppResponse();

    ippResult = ippResponse.getResponse(ByteBuffer.wrap(result));
    ippResult.setHttpStatusResponse(httpStatusLine);

    // IppResultPrinter.print(ippResult);

    client.getConnectionManager().shutdown();
    return ippResult;
}

From source file:nextflow.fs.dx.api.DxHttpClient.java

/**
 * Issues a request against the specified resource and returns either the
 * text of the response or the parsed JSON of the response (depending on
 * whether parseResponse is set).// ww w .j a va 2 s  .  c om
 */
private ParsedResponse requestImpl(String resource, String data, boolean parseResponse) throws IOException {
    HttpPost request = new HttpPost(apiserver + resource);

    request.setHeader("Content-Type", "application/json");
    request.setHeader("Authorization", securityContext.get("auth_token_type").textValue() + " "
            + securityContext.get("auth_token").textValue());
    request.setEntity(new StringEntity(data));

    // Retry with exponential backoff
    int timeout = 1;

    for (int i = 0; i <= NUM_RETRIES; i++) {
        HttpResponse response = null;
        boolean okToRetry = false;

        try {
            response = httpclient.execute(request);
        } catch (ClientProtocolException e) {
            log.error(errorMessage("POST", resource, e.toString(), timeout, i + 1, NUM_RETRIES));
        } catch (IOException e) {
            log.error(errorMessage("POST", resource, e.toString(), timeout, i + 1, NUM_RETRIES));
        }

        if (response != null) {
            int statusCode = response.getStatusLine().getStatusCode();

            HttpEntity entity = response.getEntity();

            if (statusCode == HttpStatus.SC_OK) {
                // 200 OK

                byte[] value = EntityUtils.toByteArray(entity);
                int realLength = value.length;
                if (entity.getContentLength() >= 0 && realLength != entity.getContentLength()) {
                    String errorStr = "Received response of " + realLength + " bytes but Content-Length was "
                            + entity.getContentLength();
                    log.error(errorMessage("POST", resource, errorStr, timeout, i + 1, NUM_RETRIES));
                } else {
                    if (parseResponse) {
                        JsonNode responseJson = null;
                        try {
                            responseJson = DxJson.parseJson(new String(value, "UTF-8"));
                        } catch (JsonProcessingException e) {
                            if (entity.getContentLength() < 0) {
                                // content-length was not provided, and the
                                // JSON could not be parsed. Retry since
                                // this is a streaming request from the
                                // server that probably just encountered a
                                // transient error.
                            } else {
                                throw e;
                            }
                        }
                        if (responseJson != null) {
                            return new ParsedResponse(null, responseJson);
                        }
                    } else {
                        return new ParsedResponse(new String(value, "UTF-8"), null);
                    }
                }
            } else {
                // Non-200 status codes.

                // 500 InternalError should get retried. 4xx errors should
                // be considered not recoverable.
                if (statusCode < 500) {
                    throw new IOException(EntityUtils.toString(entity));
                } else {
                    log.error(errorMessage("POST", resource, EntityUtils.toString(entity), timeout, i + 1,
                            NUM_RETRIES));
                }
            }
        }

        if (i < NUM_RETRIES) {
            try {
                Thread.sleep(timeout * 1000);
            } catch (InterruptedException e) {
                log.debug("Stopped sleep caused by: {}", e.getMessage());
            }
            timeout *= 2;
        }
    }

    throw new IOException("POST " + resource + " failed");
}

From source file:mobi.dlys.android.core.net.http.handler.BinaryHttpResponseHandler.java

@Override
public void sendResponseMessage(HttpResponse response, HttpUriRequest request) {
    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;//ww  w  . ja v  a 2 s .c o m
    }
    // Header contentTypeHeader = contentTypeHeaders[0];
    // boolean foundAllowedContentType = false;
    // for (String anAllowedContentType : mAllowedContentTypes)
    // {
    // String value = contentTypeHeader.getValue();
    // if (Pattern.matches(anAllowedContentType, value))
    // {
    // foundAllowedContentType = true;
    // }
    // }
    // foundAllowedContentType = true;
    // if (!foundAllowedContentType)
    // {
    // //Content-Type not in allowed list, ABORT!
    // 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, (byte[]) null);
    }

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

From source file:ezid.EZIDService.java

/**
 * Log into the EZID service using account credentials provided by EZID. The cookie
 * returned by EZID is cached in a local CookieStore for the duration of the EZIDService,
 * and so subsequent calls using this instance of the service will function as
 * fully authenticated. An exception is thrown if authentication fails.
 *
 * @param username to identify the user account from EZID
 * @param password the secret password for this account
 *
 * @throws EZIDException if authentication fails for any reason
 *//*from w ww  .j av  a  2s  .  co m*/
public void login(String username, String password) throws EZIDException {
    this.username = username;
    this.password = password;
    String msg;
    try {
        URI serviceUri = new URI(LOGIN_SERVICE);
        HttpHost targetHost = new HttpHost(serviceUri.getHost(), serviceUri.getPort(), serviceUri.getScheme());
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(username, password));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING....
        //System.out.println("authCache: " + authCache.toString());

        ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
            public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                } else {
                    return null;
                }
            }
        };
        byte[] body = null;

        HttpGet httpget = new HttpGet(LOGIN_SERVICE);
        body = httpclient.execute(httpget, handler, localcontext);
        String message = new String(body);
        msg = parseIdentifierResponse(message);

        // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING....
        /*
                org.apache.http.client.CookieStore cookieStore = httpclient.getCookieStore();
        System.out.println("\n\nCookies : ");
        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
        System.out.println("Cookie: " + cookies.get(i));
        } */

    } catch (URISyntaxException e) {
        //System.out.println("URI SyntaxError Exception in LOGIN");
        throw new EZIDException("Bad syntax for uri: " + LOGIN_SERVICE, e);
    } catch (ClientProtocolException e) {
        //System.out.println("ClientProtocol Exception in LOGIN");
        throw new EZIDException(e);
    } catch (IOException e) {
        //System.out.println("IO Exception in LOGIN");
        throw new EZIDException(e);
    }
    //System.out.println("Seems to be a successful LOGIN, msg= " + msg.toString());
}

From source file:com.swisscom.refimpl.boundary.MIB3Client.java

public AuthSubscriptionDomain retrieveAuthSubscription(String merchantId, String easypayAuthId)
        throws IOException, HttpException {
    HttpGet method = new HttpGet(MIB3Client.AUTHSUBSCRIPTIONS_URL + "/" + easypayAuthId);
    //out.add(method);
    addSignature(method, "GET", "/authsubscriptions/" + easypayAuthId, merchantId,
            "application/vnd.ch.swisscom.easypay.authsubscription+json", null);
    HttpResponse response = httpClient.execute(method);
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readValue(EntityUtils.toByteArray(response.getEntity()), AuthSubscriptionDomain.class);
}

From source file:com.chatsdk.kenai.jbosh.ApacheHTTPResponse.java

/**
 * Await the response, storing the result in the instance variables of
 * this class when they arrive.//from www. j a v  a  2  s.co m
 *
 * @throws InterruptedException if interrupted while awaiting the response
 * @throws BOSHException on communication failure
 */
private synchronized void awaitResponse() throws BOSHException {
    HttpEntity entity = null;
    try {
        HttpResponse httpResp = client.execute(post, context);
        entity = httpResp.getEntity();
        byte[] data = EntityUtils.toByteArray(entity);
        String encoding = entity.getContentEncoding() != null ? entity.getContentEncoding().getValue() : null;
        if (ZLIBCodec.getID().equalsIgnoreCase(encoding)) {
            data = ZLIBCodec.decode(data);
        } else if (GZIPCodec.getID().equalsIgnoreCase(encoding)) {
            data = GZIPCodec.decode(data);
        }
        body = StaticBody.fromString(new String(data, CHARSET));
        statusCode = httpResp.getStatusLine().getStatusCode();
        sent = true;
    } catch (IOException iox) {
        abort();
        toThrow = new BOSHException("Could not obtain response", iox);
        throw (toThrow);
    } catch (RuntimeException ex) {
        abort();
        throw (ex);
    }
}