Example usage for org.apache.http.entity ByteArrayEntity ByteArrayEntity

List of usage examples for org.apache.http.entity ByteArrayEntity ByteArrayEntity

Introduction

In this page you can find the example usage for org.apache.http.entity ByteArrayEntity ByteArrayEntity.

Prototype

public ByteArrayEntity(byte[] bArr) 

Source Link

Usage

From source file:com.android.volley.ssl.SslHttpStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *//*from w w  w. j  av  a2  s  .c  o m*/
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setMultiPartBody(postRequest, request);
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setMultiPartBody(putRequest, request);
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    // Added in source code of Volley libray.
    /*case Method.PATCH: {
       HttpPatch patchRequest = new HttpPatch(request.getUrl());
       patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }*/
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

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

/**
 * Create and send a new request to the upstream connection manager,
 * providing deferred access to the results to be returned.
 *
 * @param client client instance to use when sending the request
 * @param cfg client configuration/*from ww  w.  j a  v a2 s  .  c  om*/
 * @param params connection manager parameters from the session creation
 *  response, or {@code null} if the session has not yet been established
 * @param request body of the client request
 */
ApacheHTTPResponse(final HttpClient client, final BOSHClientConfig cfg, final CMSessionParams params,
        final AbstractBody request) {
    super();
    this.client = client;
    this.context = new BasicHttpContext();
    this.post = new HttpPost(cfg.getURI().toString());
    this.sent = false;

    try {
        String xml = request.toXML();
        byte[] data = xml.getBytes(CHARSET);

        String encoding = null;
        if (cfg.isCompressionEnabled() && params != null) {
            AttrAccept accept = params.getAccept();
            if (accept != null) {
                if (accept.isAccepted(ZLIBCodec.getID())) {
                    encoding = ZLIBCodec.getID();
                    data = ZLIBCodec.encode(data);
                } else if (accept.isAccepted(GZIPCodec.getID())) {
                    encoding = GZIPCodec.getID();
                    data = GZIPCodec.encode(data);
                }
            }
        }

        ByteArrayEntity entity = new ByteArrayEntity(data);
        entity.setContentType(CONTENT_TYPE);
        if (encoding != null) {
            entity.setContentEncoding(encoding);
        }
        post.setEntity(entity);
        if (cfg.isCompressionEnabled()) {
            post.setHeader(ACCEPT_ENCODING, ACCEPT_ENCODING_VAL);
        }
    } catch (Exception e) {
        toThrow = new BOSHException("Could not generate request", e);
    }
}

From source file:com.infostretch.volydemo.network.volly.ssl.SslHttpStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *//*from   w ww .ja  v a 2s  . c  o m*/
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setMultiPartBody(postRequest, request);
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setMultiPartBody(putRequest, request);
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    // Added in source code of Volley libray.
    case Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(request.getUrl());
        patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:org.hydracache.server.httpd.handler.BaseHttpMethodHandler.java

protected ByteArrayEntity generateBinaryEntityForData(Data data) throws IOException {
    Buffer buffer = ProtocolUtils.encodeDataMessage(messageEncoder, data);

    ByteArrayEntity body = new ByteArrayEntity(buffer.toByteArray());

    body.setContentType(BINARY_RESPONSE_CONTENT_TYPE);
    return body;/* www. j av a 2  s .  c  om*/
}

From source file:org.esigate.http.HttpClientRequestExecutorTest.java

private HttpResponse createMockGzippedResponse(String content) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = new GZIPOutputStream(baos);
    byte[] uncompressedBytes = content.getBytes();
    gzos.write(uncompressedBytes, 0, uncompressedBytes.length);
    gzos.close();/*  ww  w  .  j  a v  a 2 s.  c  om*/
    byte[] compressedBytes = baos.toByteArray();
    ByteArrayEntity httpEntity = new ByteArrayEntity(compressedBytes);
    httpEntity.setContentType("text/html; charset=ISO-8859-1");
    httpEntity.setContentEncoding("gzip");
    StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("p", 1, 2), HttpStatus.SC_OK, "OK");
    BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine);
    httpResponse.addHeader("Content-type", "text/html; charset=ISO-8859-1");
    httpResponse.addHeader("Content-encoding", "gzip");
    httpResponse.setEntity(httpEntity);
    return httpResponse;
}

From source file:org.activiti.webservice.WebServiceSendActivitiBehavior.java

public void execute(ActivityExecution execution) throws Exception {
    String endpointUrlValue = this.getStringFromField(this.endpointUrl, execution);
    String languageValue = this.getStringFromField(this.language, execution);
    String payloadExpressionValue = this.getStringFromField(this.payloadExpression, execution);
    String resultVariableValue = this.getStringFromField(this.resultVariable, execution);
    String usernameValue = this.getStringFromField(this.username, execution);
    String passwordValue = this.getStringFromField(this.password, execution);

    ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines();
    Object payload = scriptingEngines.evaluate(payloadExpressionValue, languageValue, execution);

    if (endpointUrlValue.startsWith("vm:")) {
        LocalWebServiceClient client = this.getWebServiceContext().getClient();
        WebServiceMessage message = new DefaultWebServiceMessage(payload, this.getWebServiceContext());
        WebServiceMessage resultMessage = client.send(endpointUrlValue, message);
        Object result = resultMessage.getPayload();
        if (resultVariableValue != null) {
            execution.setVariable(resultVariableValue, result);
        }//from   ww  w .  j  a va  2  s.  co m

    } else {

        HttpClientBuilder clientBuilder = HttpClientBuilder.create();

        if (usernameValue != null && passwordValue != null) {
            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(usernameValue,
                    passwordValue);
            provider.setCredentials(new AuthScope("localhost", -1, "webservice-realm"), credentials);
            clientBuilder.setDefaultCredentialsProvider(provider);
        }

        HttpClient client = clientBuilder.build();

        HttpPost request = new HttpPost(endpointUrlValue);

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(payload);
            oos.flush();
            oos.close();

            request.setEntity(new ByteArrayEntity(baos.toByteArray()));

        } catch (Exception e) {
            throw new ActivitiException("Error setting message payload", e);
        }

        byte[] responseBytes = null;
        try {
            // execute the POST request
            HttpResponse response = client.execute(request);
            responseBytes = IOUtils.toByteArray(response.getEntity().getContent());

        } finally {
            // release any connection resources used by the method
            request.releaseConnection();
        }

        if (responseBytes != null) {
            try {
                ByteArrayInputStream in = new ByteArrayInputStream(responseBytes);
                ObjectInputStream is = new ObjectInputStream(in);
                Object result = is.readObject();
                if (resultVariableValue != null) {
                    execution.setVariable(resultVariableValue, result);
                }
            } catch (Exception e) {
                throw new ActivitiException("Failed to read response value", e);
            }
        }
    }

    this.leave(execution);
}

From source file:org.hydracache.server.httpd.handler.HttpPutMethodHandlerTest.java

private void stubGetByteArrayEntityFromRequest(byte[] data) {
    when(mockRequest.getEntity()).thenReturn(new ByteArrayEntity(data));
}

From source file:com.arcbees.vcs.github.GitHubApi.java

@Override
public Comment postComment(Integer pullRequestId, String comment) throws IOException {
    String requestUrl = apiPaths.addComment(repositoryOwner, repositoryName, pullRequestId);

    HttpPost request = new HttpPost(requestUrl);
    request.setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()));
    request.setEntity(// ww  w. j  ava2 s. c  om
            new ByteArrayEntity(gson.toJson(new GitHubCreateComment(comment)).getBytes(Charsets.UTF_8)));

    return processResponse(httpClient, request, credentials, gson, GitHubComment.class);
}

From source file:com.basho.riak.client.util.ClientHelper.java

/**
 * See// www .ja  v  a2s .  c o m
 * {@link RiakClient#setBucketSchema(String, com.basho.riak.client.http.RiakBucketInfo, RequestMeta)}
 */
public HttpResponse setBucketSchema(String bucket, JSONObject schema, RequestMeta meta) {
    if (schema == null) {
        schema = new JSONObject();
    }
    if (meta == null) {
        meta = new RequestMeta();
    }

    meta.setHeader(Constants.HDR_ACCEPT, Constants.CTYPE_JSON);

    HttpPut put = new HttpPut(ClientUtils.makeURI(config, bucket));
    ByteArrayEntity entity = new ByteArrayEntity(utf8StringToBytes(schema.toString()));
    entity.setContentType(Constants.CTYPE_JSON);
    put.setEntity(entity);

    return executeMethod(bucket, null, put, meta);
}

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

protected void asyncDeliver(final RHTTPResponse response) {
    new Thread() {
        @Override/*from w w w. j a v a 2 s .c  om*/
        public void run() {
            try {
                HttpPost deliver = new HttpPost(gatewayPath + "/" + urlEncode(getTargetId()) + "/deliver");
                deliver.setEntity(new ByteArrayEntity(response.getFrameBytes()));
                getLogger().debug("Client {} deliver sent to gateway, response {}", getTargetId(), response);
                HttpResponse httpResponse = httpClient.execute(deliver);
                int statusCode = httpResponse.getStatusLine().getStatusCode();
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null)
                    entity.consumeContent();
                if (statusCode == HttpStatus.SC_UNAUTHORIZED)
                    notifyConnectRequired();
                else if (statusCode != HttpStatus.SC_OK)
                    notifyDeliverException(response);
            } catch (IOException x) {
                getLogger().debug("", x);
                notifyDeliverException(response);
            }
        }
    }.start();
}