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.androidex.volley.toolbox.HttpClientStack.java

private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request)
        throws IOException, AuthFailureError {

    if (request instanceof MultiPartRequest) {
        ProgressListener progressListener = null;
        if (request instanceof ProgressListener) {
            progressListener = (ProgressListener) request;
        }//w w w  . j a v a  2 s .  co m
        MultipartProgressEntity multipartEntity = new MultipartProgressEntity();
        multipartEntity.setListener(progressListener);
        final String charset = ((MultiPartRequest<?>) request).getProtocolCharset();
        httpRequest.addHeader(HEADER_CONTENT_TYPE,
                String.format(CONTENT_TYPE_MULTIPART, charset, multipartEntity.getBoundary()));

        final Map<String, MultiPartParam> multipartParams = ((MultiPartRequest<?>) request)
                .getMultipartParams();
        final Map<String, String> filesToUpload = ((MultiPartRequest<?>) request).getFilesToUpload();

        for (String key : multipartParams.keySet()) {
            multipartEntity.addPart(new StringPart(key, multipartParams.get(key).value));
        }

        for (String key : filesToUpload.keySet()) {
            File file = new File(filesToUpload.get(key));

            if (!file.exists()) {
                throw new IOException(String.format("File not found: %s", file.getAbsolutePath()));
            }

            if (file.isDirectory()) {
                throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath()));
            }

            FilePart filePart = new FilePart(key, file, null, null);
            multipartEntity.addPart(filePart);
        }
        httpRequest.setEntity(multipartEntity);

    } else {
        httpRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        byte[] body = request.getBody();
        if (body != null) {
            HttpEntity entity = new ByteArrayEntity(body);
            httpRequest.setEntity(entity);
        }
    }
}

From source file:org.wso2.dss.integration.test.odata.ODataSuperTenantUserTestCase.java

private static int sendPOST(String endpoint, String content, String acceptType) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(endpoint);
    httpPost.setHeader("Accept", acceptType);
    if (null != content) {
        HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(httpEntity);/*from w  ww  . j a  va  2 s  . c om*/
    }
    HttpResponse httpResponse = httpClient.execute(httpPost);
    return httpResponse.getStatusLine().getStatusCode();
}

From source file:org.soyatec.windowsazure.blob.internal.BlockBlob.java

boolean uploadData(IBlobProperties blobProperties, BlobStream stream, long length, boolean overwrite,
        String eTag, NameValueCollection queryParameters, int action) throws Exception {

    // fix root container
    boolean isRoot = container.getName().equals(IBlobContainer.ROOT_CONTAINER);
    String containerName = isRoot ? "" : container.getName();
    ResourceUriComponents uriComponents = new ResourceUriComponents(container.getAccountName(), containerName,
            blobProperties.getName());//from   ww  w .  j a v  a  2  s.c o  m
    URI blobUri = HttpUtilities.createRequestUri(container.getBaseUri(), container.isUsePathStyleUris(),
            container.getAccountName(), containerName, blobProperties.getName(), container.getTimeout(),
            queryParameters, uriComponents, container.getCredentials());

    if (SSLProperties.isSSL()) {
        try {
            URI newBlobUri = new URI("https", null, blobUri.getHost(), 443, blobUri.getPath(),
                    blobUri.getQuery(), blobUri.getFragment());
            blobUri = newBlobUri;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    HttpRequest request = createHttpRequestForPutBlob(blobUri, HttpMethod.Put, blobProperties, length,
            overwrite, eTag);
    // if (isRoot) {
    // request.addHeader(HeaderNames.ApiVersion,
    // XmsVersion.VERSION_2009_07_17);
    // }
    request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2009_09_19);
    if (action == BLOB_ACTION || action == BLOCK_ACTION) { // small blob or
        // block
        request.addHeader(HeaderNames.BlobType, BlobType.BlockBlob.getLiteral());
    }

    boolean retval = false;
    BlobStream requestStream = new BlobMemoryStream();
    Utilities.copyStream(stream, requestStream, (int) length);
    byte[] body = requestStream.getBytes();
    ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(body));

    processMD5(blobProperties, request, body, action);

    container.credentials.signRequest(request, uriComponents);

    HttpWebResponse response = null;
    if (SSLProperties.isSSL()) {
        SSLSocketFactory factory = SslUtil.createSSLSocketFactory(SSLProperties.getKeyStore(),
                SSLProperties.getKeyStorePasswd(), SSLProperties.getTrustStore(),
                SSLProperties.getTrustStorePasswd(), SSLProperties.getKeyAlias());
        response = HttpUtilities.getSSLReponse((HttpUriRequest) request, factory);
    } else {
        response = HttpUtilities.getResponse(request);
    }
    if (response.getStatusCode() == HttpStatus.SC_CREATED) {
        retval = true;
    } else if (!overwrite && (response.getStatusCode() == HttpStatus.SC_PRECONDITION_FAILED
            || response.getStatusCode() == HttpStatus.SC_NOT_MODIFIED)) {
        retval = false;
    } else {
        retval = false;
        HttpUtilities.processUnexpectedStatusCode(response);
    }

    blobProperties.setLastModifiedTime(response.getLastModified());
    blobProperties.setETag(response.getHeader(HeaderNames.ETag));
    requestStream.close();
    response.close();
    return retval;
}

From source file:com.ocp.picasa.GDataClient.java

private ByteArrayEntity getCompressedEntity(byte[] data) throws IOException {
    ByteArrayEntity entity;//from w  ww  .  ja v a  2s.c om
    if (data.length >= MIN_GZIP_SIZE) {
        ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(data.length / 2);
        GZIPOutputStream gzipOutput = new GZIPOutputStream(byteOutput);
        gzipOutput.write(data);
        gzipOutput.close();
        entity = new ByteArrayEntity(byteOutput.toByteArray());
    } else {
        entity = new ByteArrayEntity(data);
    }
    return entity;
}

From source file:com.volley.air.toolbox.HttpClientStack.java

private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request)
        throws IOException, AuthFailureError {

    if (request instanceof MultiPartRequest) {
        ProgressListener progressListener = null;
        if (request instanceof ProgressListener) {
            progressListener = (ProgressListener) request;
        }/*from  w  ww. jav  a2s.c  om*/
        MultipartProgressEntity multipartEntity = new MultipartProgressEntity();
        multipartEntity.setListener(progressListener);
        final String charset = ((MultiPartRequest<?>) request).getProtocolCharset();
        httpRequest.addHeader(HEADER_CONTENT_TYPE,
                String.format(CONTENT_TYPE_MULTIPART, charset, multipartEntity.getBoundary()));

        final Map<String, MultiPartParam> multipartParams = ((MultiPartRequest<?>) request)
                .getMultipartParams();
        final Map<String, String> filesToUpload = ((MultiPartRequest<?>) request).getFilesToUpload();

        for (Map.Entry<String, MultiPartParam> entry : multipartParams.entrySet()) {
            multipartEntity.addPart(new StringPart(entry.getKey(), entry.getValue().value));
        }

        for (Map.Entry<String, String> entry : filesToUpload.entrySet()) {
            File file = new File(entry.getValue());

            if (!file.exists()) {
                throw new IOException(String.format("File not found: %s", file.getAbsolutePath()));
            }

            if (file.isDirectory()) {
                throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath()));
            }

            FilePart filePart = new FilePart(entry.getKey(), file, null, null);
            multipartEntity.addPart(filePart);
        }
        httpRequest.setEntity(multipartEntity);

    } else {
        httpRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        byte[] body = request.getBody();
        if (body != null) {
            HttpEntity entity = new ByteArrayEntity(body);
            httpRequest.setEntity(entity);
        }
    }
}

From source file:com.github.wnameless.spring.bulkapi.test.BulkApiTest.java

@Test
public void bulkRequestCanNotContainBulkPathAsUrl() throws Exception {
    BulkRequest req = new BulkRequest();
    BulkOperation op = new BulkOperation();
    op.setUrl(bulkPath);/*w  ww. j  a v a  2 s .c  om*/
    op.setMethod("GET");
    op.getHeaders().put("Authorization", "Basic " + Base64Utils.encodeToString("user:password".getBytes()));
    req.getOperations().add(op);

    HttpEntity entity = new ByteArrayEntity(mapper.writeValueAsString(req).getBytes("UTF-8"));
    post.setEntity(entity);
    HttpResponse response = client.execute(post);

    assertTrue(422 == response.getStatusLine().getStatusCode());
}

From source file:com.mnxfst.testing.activities.http.TestHTTPRequestActivity.java

public void testExecuteHTTPRequest() throws HttpException, IOException {

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, false);

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
    HttpContext context = new BasicHttpContext(null);
    HttpHost host = new HttpHost("www.heise.de", 80);

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    try {/*from  w ww.  j  a  v  a2  s .c  om*/

        HttpEntity[] requestBodies = { new StringEntity("This is the first test request", "UTF-8"),
                new ByteArrayEntity("This is the second test request".getBytes("UTF-8")),
                new InputStreamEntity(new ByteArrayInputStream(
                        "This is the third test request (will be chunked)".getBytes("UTF-8")), -1) };

        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                // Required protocol interceptors
                new RequestContent(), new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

        for (int i = 0; i < requestBodies.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");
            request.setEntity(requestBodies[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }

}

From source file:com.nridge.ds.solr.SolrConfig.java

/**
 * Updates the Solr configuration for the search cluster with a single batch
 * operation.  This method should be used to update the request handler associated
 * with a schema.  You should ensure that this method is invoked prior to schema fields
 * referencing a new field type.//from ww  w .j av  a 2s  . com
 *
 * Field type in a <i>Document</i> are modeled in a hierarchy consisting of a
 * common set of fields (name, class, etc.) and relationships representing
 * Solr component configurations.  Contained within each component relationship
 * document are configuration parameters (which are tables with columns that
 * will depend on the class selected).
 *
 * @see <a href="http://lucene.apache.org/solr/guide/7_6/config-api.html">Solr Config API</a>
 *
 * @param aDocument Document of type RESPONSE_CONFIG_REQUEST_HANDLER or
 *                  RESPONSE_CONFIG_SEARCH_COMPONENT.
 *
 * @throws DSException Data source exception.
 */
public void update(Document aDocument) throws DSException {
    Logger appLogger = mAppMgr.getLogger(this, "update");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(String.format("{%n"));
    update(stringBuilder, aDocument);
    stringBuilder.append(String.format("%n}%n"));
    String jsonPayload = stringBuilder.toString();

    // Construct our query URI string

    String baseSolrURL = mSolrDS.getBaseURL(true);
    String solrURI = baseSolrURL + "/config";

    // Next, we will execute the HTTP POST request with the Solr schema API service.

    CloseableHttpResponse httpResponse = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(solrURI);
    httpPost.addHeader("Content-type", CONTENT_TYPE_JSON);

    try {
        HttpEntity httpEntity = new ByteArrayEntity(jsonPayload.getBytes(StandardCharsets.UTF_8));
        httpPost.setEntity(httpEntity);
        httpResponse = httpClient.execute(httpPost);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        String msgStr = String.format("%s [%d]: %s", solrURI, statusCode, statusLine);
        appLogger.debug(msgStr);
        if (statusCode == HttpStatus.SC_OK) {
            httpEntity = httpResponse.getEntity();
            EntityUtils.consume(httpEntity);
        } else {
            msgStr = String.format("%s [%d]: %s", solrURI, statusCode, statusLine);
            appLogger.error(msgStr);
            appLogger.debug(jsonPayload);
            throw new DSException(msgStr);
        }
    } catch (IOException e) {
        String msgStr = String.format("%s (%s): %s", solrURI, aDocument.getName(), e.getMessage());
        appLogger.error(msgStr, e);
        throw new DSException(msgStr);
    } finally {
        if (httpResponse != null)
            IO.closeQuietly(httpResponse);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

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

/**
 * This test case executes a series of simple POST requests with content length 
 * delimited content. //from w  w  w .j  a v  a 2  s .c o m
 */
@LargeTest
public void testSimpleHttpPostsWithContentLength() 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();

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