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:org.votingsystem.util.HttpHelper.java

public <T> T getData(Class<T> type, TypeReference typeReference, String serverURL, String mediaType)
        throws Exception {
    log.info("getData - contentType: " + mediaType + " - serverURL: " + serverURL);
    CloseableHttpResponse response = null;
    HttpGet httpget = null;/*from  w  w w  .  j a va2 s. c  o  m*/
    String responseContentType = null;
    httpget = new HttpGet(serverURL);
    if (mediaType != null)
        httpget.setHeader("Content-Type", mediaType);
    response = httpClient.execute(httpget);
    log.info("----------------------------------------");
    /*Header[] headers = response.getAllHeaders();
    for (int i = 0; i < headers.length; i++) { System.out.println(headers[i]); }*/
    log.info(response.getStatusLine().toString() + " - connManager stats: "
            + connManager.getTotalStats().toString());
    log.info("----------------------------------------");
    Header header = response.getFirstHeader("Content-Type");
    if (header != null)
        responseContentType = header.getValue();
    try {
        byte[] responseBytes = EntityUtils.toByteArray(response.getEntity());
        if (ResponseVS.SC_OK == response.getStatusLine().getStatusCode()) {
            if (type != null)
                return JSON.getMapper().readValue(responseBytes, type);
            else
                return JSON.getMapper().readValue(responseBytes, typeReference);
        } else {
            MessageDto messageDto = null;
            String responseStr = null;
            if (responseContentType != null && responseContentType.contains(MediaTypeVS.JSON))
                messageDto = JSON.getMapper().readValue(responseBytes, MessageDto.class);
            else
                responseStr = new String(responseBytes, StandardCharsets.UTF_8);
            switch (response.getStatusLine().getStatusCode()) {
            case ResponseVS.SC_NOT_FOUND:
                throw new NotFoundExceptionVS(responseStr, messageDto);
            case ResponseVS.SC_ERROR_REQUEST_REPEATED:
                throw new RequestRepeatedExceptionVS(responseStr, messageDto);
            case ResponseVS.SC_ERROR_REQUEST:
                throw new BadRequestExceptionVS(responseStr, messageDto);
            case ResponseVS.SC_ERROR:
                throw new ServerExceptionVS(EntityUtils.toString(response.getEntity()), messageDto);
            default:
                throw new ExceptionVS(responseStr, messageDto);
            }
        }
    } finally {
        if (response != null)
            response.close();
    }
}

From source file:com.alibaba.shared.django.DjangoClient.java

protected DjangoMessage executeRequest(Supplier<HttpUriRequest> requestSupplier, boolean canRetry)
        throws IOException, URISyntaxException {
    DjangoMessage message = null;//from w w w  .  j a va 2s .c om
    try {
        HttpResponse response = getHttpClient().execute(requestSupplier.get());
        if (response.getStatusLine().getStatusCode() == 200) {
            message = JSON.parseObject(EntityUtils.toByteArray(response.getEntity()), DjangoMessage.class);
            if (canRetry && message != null && message.isTokenExpired()) {
                refreshToken();
                message = executeRequest(requestSupplier, false);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return message;
}

From source file:com.dream.messaging.sender.http.HttpClientTemplate.java

/**
 * byte?//ww w  .  ja  va 2s .c  om
 * @param request
 * @return
 * @throws IOException
 */
protected byte[] execute(HttpRequest request) throws IOException {
    if (logger.isInfoEnabled()) {
        logger.info("Going to send a http message:" + request.getRequestLine());
    }

    HttpResponse response;
    byte[] bytes = null;
    try {
        response = httpClient.execute((HttpUriRequest) request);
        HttpEntity entity = response.getEntity();
        bytes = EntityUtils.toByteArray(entity);
    } catch (Exception e) {
        logger.error("The communication to the http endpoint faild...", e);
        throw new IOException("The communication to the http endpoint faild...");
    }

    if (logger.isInfoEnabled()) {
        logger.info("Recieved a http message:" + response);
    }
    return bytes;
}

From source file:org.teleal.cling.transport.impl.apache.StreamClientImpl.java

protected ResponseHandler<StreamResponseMessage> createResponseHandler() {
    return new ResponseHandler<StreamResponseMessage>() {
        public StreamResponseMessage handleResponse(final HttpResponse httpResponse) throws IOException {

            StatusLine statusLine = httpResponse.getStatusLine();
            log.fine("Received HTTP response: " + statusLine);

            // Status
            UpnpResponse responseOperation = new UpnpResponse(statusLine.getStatusCode(),
                    statusLine.getReasonPhrase());

            // Message
            StreamResponseMessage responseMessage = new StreamResponseMessage(responseOperation);

            // Headers
            responseMessage.setHeaders(new UpnpHeaders(HeaderUtil.get(httpResponse)));

            // Body
            HttpEntity entity = httpResponse.getEntity();
            if (entity == null || entity.getContentLength() == 0)
                return responseMessage;

            if (responseMessage.isContentTypeMissingOrText()) {
                log.fine("HTTP response message contains text entity");
                responseMessage.setBody(UpnpMessage.BodyType.STRING, EntityUtils.toString(entity));
            } else {
                log.fine("HTTP response message contains binary entity");
                responseMessage.setBody(UpnpMessage.BodyType.BYTES, EntityUtils.toByteArray(entity));
            }/*from  w w w  .j ava2s  . com*/

            return responseMessage;
        }
    };
}

From source file:org.red5.client.net.remoting.DSRemotingClient.java

/**
 * Invoke a method synchronously on the remoting server.
 * //from www .  jav  a2s.  c  o m
 * @param method Method name
 * @param params Parameters passed to method
 * @return the result of the method call
 */
@Override
public Object invokeMethod(String method, Object[] params) {
    log.debug("invokeMethod url: {}", (url + appendToUrl));
    IoBuffer resultBuffer = null;
    IoBuffer data = encodeInvoke(method, params);
    //setup POST
    HttpPost post = null;
    try {
        post = new HttpPost(url + appendToUrl);
        post.addHeader("Content-Type", CONTENT_TYPE);
        post.setEntity(new InputStreamEntity(data.asInputStream(), data.limit()));
        // execute the method
        HttpResponse response = client.execute(post);
        int code = response.getStatusLine().getStatusCode();
        log.debug("HTTP response code: {}", code);
        if (code / 100 != 2) {
            throw new RuntimeException("Didn't receive success from remoting server");
        } else {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //fix for Trac #676
                int contentLength = (int) entity.getContentLength();
                //default the content length to 16 if post doesn't contain a good value
                if (contentLength < 1) {
                    contentLength = 16;
                }
                // get the response as bytes
                byte[] bytes = EntityUtils.toByteArray(entity);
                resultBuffer = IoBuffer.wrap(bytes);
                resultBuffer.flip();
                Object result = decodeResult(resultBuffer);
                if (result instanceof RecordSet) {
                    // Make sure we can retrieve paged results
                    ((RecordSet) result).setRemotingClient(this);
                }
                return result;
            }
        }
    } catch (Exception ex) {
        log.error("Error while invoking remoting method.", ex);
        post.abort();
    } finally {
        if (resultBuffer != null) {
            resultBuffer.free();
            resultBuffer = null;
        }
        data.free();
        data = null;
    }
    return null;
}

From source file:com.bamobile.fdtks.util.Tools.java

public static byte[] getFileDataFromURL(String imageUrl) {
    if (imageUrl != null && imageUrl.length() > 0) {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(imageUrl.replace(" ", "%20"));
        try {/*from   w  w w  .  j a  va 2s  .  c  o m*/
            HttpResponse response = client.execute(get);
            byte[] content = EntityUtils.toByteArray(response.getEntity());
            return content;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.ibm.ws.lars.rest.RepositoryContext.java

public byte[] doGetAsByteArray(String url, int expectedStatusCode) throws ClientProtocolException, IOException {
    HttpGet get = new HttpGet(fullURL + url);
    HttpResponse response = httpClient.execute(targetHost, get, context);

    assertStatusCode(expectedStatusCode, response);
    return EntityUtils.toByteArray(response.getEntity());
}

From source file:com.codeasylum.stress.api.HttpTask.java

@Override
public void execute(long timeDifferential, int hostIndex, String hostId, Ouroboros ouroboros,
        ExchangeTransport exchangeTransport) throws IOException, ScriptInterpolationException {

    if (isEnabled() && ouroboros.isEnabled()) {

        HttpUriRequest httpRequest;/*www .ja va 2s.c  om*/
        ResponseCarrier responseCarrier;
        URI requestURI;
        StringBuilder uriBuilder;
        String requestMimeType;
        String requestCharSet;
        String requestBody;
        boolean validated = true;
        long startTime;

        if ((portAttribute.getScript() == null) || (portAttribute.getScript().length() == 0)) {
            throw new TaskExecutionException("The %s(%s) has no http port value configured",
                    HttpTask.class.getSimpleName(), getName());
        }

        uriBuilder = new StringBuilder("http://").append(serverAttribute.get(this)).append(':')
                .append(portAttribute.get(this)).append('/').append(pathAttribute.get(this));
        try {
            requestURI = new URI(uriBuilder.toString());
        } catch (URISyntaxException uriSyntaxException) {
            throw new TaskExecutionException(uriSyntaxException,
                    "The %s(%s) has been configured with a malformed URI(%s)", HttpTask.class.getSimpleName(),
                    getName(), uriBuilder.toString());
        }

        if ((requestMimeType = contentTypeAttribute.get(this)) != null) {

            int semiColonPos;

            if ((semiColonPos = requestMimeType.indexOf(';')) < 0) {
                requestCharSet = "utf-8";
            } else {

                int equalsPos;

                if ((equalsPos = requestMimeType.indexOf('=', semiColonPos + 1)) <= 0) {
                    throw new TaskExecutionException(
                            "The %s(%s) contains an improperly formatted content type(%s)",
                            HttpTask.class.getSimpleName(), getName(), requestMimeType);
                }

                requestCharSet = requestMimeType.substring(equalsPos + 1);
                requestMimeType = requestMimeType.substring(0, semiColonPos);
            }
        } else {
            requestMimeType = "text/plain";
            requestCharSet = "utf-8";
        }

        switch (httpMethod) {
        case GET:
            if (((requestBody = bodyAttribute.get(this)) != null) && (requestBody.length() > 0)) {
                throw new TaskExecutionException(
                        "The %s(%s) uses the 'GET' method, but has been configured with body content",
                        HttpTask.class.getSimpleName(), getName());
            }

            httpRequest = new HttpGet(requestURI);
            break;
        case PUT:
            if (((requestBody = bodyAttribute.get(this)) == null) || (requestBody.length() == 0)) {
                throw new TaskExecutionException(
                        "The %s(%s) uses the 'PUT' method, but has not been configured with any body content",
                        HttpTask.class.getSimpleName(), getName());
            }

            httpRequest = new HttpPut(requestURI);
            ((HttpPut) httpRequest).setEntity(new StringEntity(requestBody, requestCharSet));
            break;
        case POST:
            if (((requestBody = bodyAttribute.get(this)) == null) || (requestBody.length() == 0)) {
                throw new TaskExecutionException(
                        "The %s(%s) uses the 'POST' method, but has not been configured with any body content",
                        HttpTask.class.getSimpleName(), getName());
            }

            httpRequest = new HttpPost(requestURI);
            ((HttpPost) httpRequest).setEntity(new StringEntity(requestBody, requestCharSet));
            break;
        case DELETE:
            if (((requestBody = bodyAttribute.get(this)) != null) && (requestBody.length() > 0)) {
                throw new TaskExecutionException(
                        "The %s(%s) uses the 'DELETE' method, but has been configured with body content",
                        HttpTask.class.getSimpleName(), getName());
            }

            httpRequest = new HttpDelete(requestURI);
            break;
        default:
            throw new UnknownSwitchCaseException(httpMethod.name());
        }

        httpRequest.setHeader("Content-Type", requestMimeType + ";charset=" + requestCharSet);

        startTime = System.currentTimeMillis();
        try {
            responseCarrier = httpClient.execute(httpRequest, new ResponseHandler<ResponseCarrier>() {

                @Override
                public ResponseCarrier handleResponse(HttpResponse response) throws IOException {

                    HttpEntity entity;
                    Header contentTypeHeader = response.getFirstHeader("Content-Type");
                    String responseMimeType;
                    String responseCharSet;

                    if ((contentTypeHeader != null)
                            && ((responseMimeType = contentTypeHeader.getValue()) != null)) {

                        int semiColonPos;

                        if ((semiColonPos = responseMimeType.indexOf(';')) < 0) {
                            responseCharSet = "utf-8";
                        } else {

                            int equalsPos;

                            if ((equalsPos = responseMimeType.indexOf('=', semiColonPos + 1)) <= 0) {
                                throw new TaskExecutionException(
                                        "Improperly formatted content type(%s) in response", responseMimeType);
                            }

                            responseCharSet = responseMimeType.substring(equalsPos + 1);
                            responseMimeType = responseMimeType.substring(0, semiColonPos);
                        }
                    } else {
                        responseMimeType = "text/plain";
                        responseCharSet = "utf-8";

                    }

                    return new ResponseCarrier(System.currentTimeMillis(),
                            response.getStatusLine().getStatusCode(), responseMimeType, responseCharSet,
                            ((entity = response.getEntity()) == null) ? null : EntityUtils.toByteArray(entity));
                }
            });

            if (!regexpMap.isEmpty()) {

                Matcher regexpMatcher;
                String responseBody = (responseCarrier.getRawResponse() == null) ? null
                        : new String(responseCarrier.getRawResponse(), responseCarrier.getResponseCharSet());

                for (Map.Entry<String, String> regexpEntry : regexpMap.entrySet()) {
                    PropertyContext.removeKeysStartingWith(regexpEntry.getKey());

                    if (responseBody != null) {
                        if ((regexpMatcher = Pattern.compile(
                                PROPERTY_EXPANDER.expand(regexpEntry.getValue(), PropertyContext.getMap()))
                                .matcher(responseBody)).find()) {
                            PropertyContext.put(regexpEntry.getKey(), "true");
                            for (int groupIndex = 0; groupIndex <= regexpMatcher.groupCount(); groupIndex++) {
                                PropertyContext.put(regexpEntry.getKey() + '.' + groupIndex,
                                        regexpMatcher.group(groupIndex));
                            }
                        } else {
                            PropertyContext.put(regexpEntry.getKey(), "false");
                        }
                    }
                }
            }

            if (!validationMap.isEmpty()) {
                for (Map.Entry<String, String> validationEntry : validationMap.entrySet()) {
                    if (!PropertyContext.valueEquals(validationEntry.getKey(), validationEntry.getValue())) {
                        validated = false;
                        break;
                    }
                }
            }

            if ((responseKey != null) && (responseKey.length() > 0)) {
                PropertyContext.put(responseKey, new String(responseCarrier.getRawResponse()));
            }

            exchangeTransport.send(new HttpExchange(validated && (responseCarrier.getResponseCode() == 200),
                    hostId, getName(), startTime + timeDifferential,
                    responseCarrier.getResponseTimestamp() + timeDifferential,
                    responseCarrier.getResponseCode(), requestMimeType, requestCharSet, requestBody,
                    responseCarrier.getResponseMimeType(), responseCarrier.getResponseCharSet(),
                    responseCarrier.getRawResponse()));
        } catch (Exception exception) {
            exchangeTransport.send(new HttpExchange(false, hostId, getName(), startTime + timeDifferential,
                    System.currentTimeMillis() + timeDifferential, 503, requestMimeType, requestCharSet,
                    requestBody, "text/plain", "utf-8",
                    StackTraceUtilities.obtainStackTraceAsString(exception).getBytes()));

            if (!regexpMap.isEmpty()) {
                for (Map.Entry<String, String> regexpEntry : regexpMap.entrySet()) {
                    PropertyContext.removeKeysStartingWith(regexpEntry.getKey());
                }
            }

            if ((responseKey != null) && (responseKey.length() > 0)) {
                PropertyContext.remove(responseKey);
            }
        }
    }
}

From source file:com.android.unit_tests.TestHttpService.java

/**
 * This test case executes a series of simple HTTP/1.0 POST requests. 
 *//*from  w  ww.  ja va2s. co  m*/
@LargeTest
public void testSimpleHttpPostsHTTP10() throws Exception {

    int reqNo = 20;

    Random rnd = new Random();

    // Prepare some random data
    List testData = new ArrayList(reqNo);
    for (int i = 0; i < reqNo; i++) {
        int size = rnd.nextInt(5000);
        byte[] data = new byte[size];
        rnd.nextBytes(data);
        testData.add(data);
    }

    // Initialize the server-side request handler
    this.server.registerHandler("*", new HttpRequestHandler() {

        public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {

            if (request instanceof HttpEntityEnclosingRequest) {
                HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity();
                byte[] data = EntityUtils.toByteArray(incoming);

                ByteArrayEntity outgoing = new ByteArrayEntity(data);
                outgoing.setChunked(false);
                response.setEntity(outgoing);
            } else {
                StringEntity outgoing = new StringEntity("No content");
                response.setEntity(outgoing);
            }
        }

    });

    this.server.start();

    // Set protocol level to HTTP/1.0
    this.client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    HttpHost host = new HttpHost("localhost", this.server.getPort());

    try {
        for (int r = 0; r < reqNo; r++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, this.client.getParams());
            }

            BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/");
            byte[] data = (byte[]) testData.get(r);
            ByteArrayEntity outgoing = new ByteArrayEntity(data);
            post.setEntity(outgoing);

            HttpResponse response = this.client.execute(post, host, conn);
            assertEquals(HttpVersion.HTTP_1_0, response.getStatusLine().getProtocolVersion());
            byte[] received = EntityUtils.toByteArray(response.getEntity());
            byte[] expected = (byte[]) testData.get(r);

            assertEquals(expected.length, received.length);
            for (int i = 0; i < expected.length; i++) {
                assertEquals(expected[i], received[i]);
            }
            if (!this.client.keepAlive(response)) {
                conn.close();
            }
        }

        //Verify the connection metrics
        HttpConnectionMetrics cm = conn.getMetrics();
        assertEquals(reqNo, cm.getRequestCount());
        assertEquals(reqNo, cm.getResponseCount());
    } finally {
        conn.close();
        this.server.shutdown();
    }
}