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.photon.phresco.nativeapp.eshop.net.HttpRequest.java

/**
 * Send the JSON data to specified URL and get the httpResponse back
 *
 * @param sURL//w  w  w .j  a  v a  2s  . co  m
 * @param jObject
 * @return InputStream
 * @throws IOException
 */
public static InputStream post(String sURL, JSONObject jObject) throws IOException {
    HttpResponse httpResponse = null;
    InputStream is = null;

    PhrescoLogger.info(TAG + " post: " + sURL);
    PhrescoLogger.info(TAG + " jObject: " + jObject);

    HttpPost httpPostRequest = new HttpPost(sURL);
    HttpEntity entity;

    httpPostRequest.setHeader("Accept", "application/json");
    httpPostRequest.setHeader(HTTP.CONTENT_TYPE, "application/json");
    httpPostRequest.setEntity(new ByteArrayEntity(jObject.toString().getBytes("UTF-8")));
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    int timeoutConnection = TIME_OUT;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = TIME_OUT;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    httpResponse = httpClient.execute(httpPostRequest);

    if (httpResponse != null) {
        entity = httpResponse.getEntity();
        is = entity.getContent();
    }
    return is;
}

From source file:com.microsoft.services.orc.http.impl.AndroidNetworkRunnable.java

@Override
public void run() {
    AndroidHttpClient client = null;/*from   ww w . j ava  2 s . c  om*/
    try {

        String userAgent = mRequest.getHeaders().get(Constants.USER_AGENT_HEADER);

        if (userAgent == null) {
            userAgent = "";
        }

        client = AndroidHttpClient.newInstance(userAgent);

        BasicHttpEntityEnclosingRequest realRequest = new BasicHttpEntityEnclosingRequest(
                mRequest.getVerb().toString(), mRequest.getUrl().toString());
        EntityEnclosingRequestWrapper wrapper = new EntityEnclosingRequestWrapper(realRequest);

        Map<String, String> headers = mRequest.getHeaders();
        for (String key : headers.keySet()) {
            wrapper.addHeader(key, headers.get(key));
        }

        if (mRequest.getContent() != null) {
            ByteArrayEntity entity = new ByteArrayEntity(mRequest.getContent());
            wrapper.setEntity(entity);
        } else if (mRequest.getStreamedContent() != null) {
            InputStream stream = mRequest.getStreamedContent();
            InputStreamEntity entity = new InputStreamEntity(stream, mRequest.getStreamedContentSize());
            wrapper.setEntity(entity);
        }

        HttpResponse realResponse = client.execute(wrapper);
        int status = realResponse.getStatusLine().getStatusCode();

        Map<String, List<String>> responseHeaders = new HashMap<String, List<String>>();
        for (Header header : realResponse.getAllHeaders()) {
            List<String> headerValues = new ArrayList<String>();
            for (HeaderElement element : header.getElements()) {
                headerValues.add(element.getValue());
            }
            responseHeaders.put(header.getName(), headerValues);
        }

        HttpEntity entity = realResponse.getEntity();
        InputStream stream = null;

        if (entity != null) {
            stream = entity.getContent();
        }

        if (stream != null) {
            final AndroidHttpClient finalClient = client;
            Closeable closeable = new Closeable() {
                @Override
                public void close() throws IOException {
                    finalClient.close();
                }
            };

            Response response = new ResponseImpl(stream, status, responseHeaders, closeable);

            mFuture.set(response);
        } else {
            client.close();
            mFuture.set(new EmptyResponse(status, responseHeaders));
        }

    } catch (Throwable t) {
        if (client != null) {
            client.close();
        }

        mFuture.setException(t);
    }
}

From source file:com.comcast.drivethru.client.ClientExecuteTest.java

@Test
public void testExecuteSuccess() throws Exception {
    String body = "this is a response from the internet";
    HttpEntity entity = new ByteArrayEntity(body.getBytes());

    BasicHttpResponse resp = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK");
    resp.setHeader("a", "apple");
    resp.setHeader("b", "bobcat");
    resp.setHeader("Content-Type", "text/plain");
    resp.setEntity(entity);//ww w.jav  a  2  s.c  o  m

    RestRequest request = new RestRequest(new URL().setPath("/").addQuery("q", "stuff"), POST);
    request.setContentType("application/json");
    request.setBody("{ \"name\" : \"Clark\" }");
    request.addHeader("x-transaction-id", "0011223344556677");

    Capture<HttpPost> capture = EasyMock.newCapture();
    Capture<HttpPost> capture2 = EasyMock.newCapture();

    HttpClient delegate = createMock(HttpClient.class);
    expect(delegate.execute(capture(capture))).andReturn(resp);

    SecurityProvider securityProvider = createMock(SecurityProvider.class);
    securityProvider.sign(capture(capture2));
    expectLastCall();

    replay(delegate, securityProvider);

    String base = "http://www.google.com";
    DefaultRestClient client = new DefaultRestClient(base, delegate);
    client.addDefaultHeader("Fintan", "The Salmon of Knowledge");
    client.setSecurityProvider(securityProvider);

    RestResponse response = client.execute(request);
    client.close();

    assertEquals(response.getBodyString(), body);
    assertEquals(response.getStatusCode(), 200);
    assertEquals(response.getStatusMessage(), "OK");
    assertEquals(response.getContentType(), "text/plain");
    assertEquals(response.getHeaderValue("a"), "apple");
    assertEquals(response.getHeaderValue("b"), "bobcat");

    /* Verify the constructed request object */
    assertTrue(capture.hasCaptured());
    HttpPost req = capture.getValue();
    assertEquals(req.getLastHeader("Content-Type").getValue(), "application/json");
    assertEquals(req.getLastHeader("x-transaction-id").getValue(), "0011223344556677");
    assertEquals(req.getLastHeader("Fintan").getValue(), "The Salmon of Knowledge");
    assertEquals(req.getURI().toString(), "http://www.google.com/?q=stuff");

    /* Verify the "aborted" status of the request */
    assertEquals(req.isAborted(), true);

    /* Read and verify the contents of the request */
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOUtils.copy(req.getEntity().getContent(), baos);
    assertEquals(baos.toString(), "{ \"name\" : \"Clark\" }");

    /* Verify Security was called with same element */
    assertTrue(capture2.hasCaptured());
    assertSame(capture2.getValue(), req);

    verify(delegate, securityProvider);
}

From source file:at.diamonddogs.data.adapter.soap.SoapRequestAdapter.java

private void initRequest(String soapAction, SoapSerializationEnvelope envelope) {
    byte[] requestData = new byte[1];
    try {//from  w ww .  j  a v a2s.c o  m
        requestData = createRequestData(envelope);
    } catch (Throwable tr) {
        LOGGER.warn("Could not create requestdata from envelope", tr);
    }
    request.setRequestType(Type.POST);
    request.addHeaderField("User-Agent", USERAGENT);
    request.addHeaderField("SOAPAction", soapAction);
    request.addHeaderField("Content-Type", "text/xml");
    request.addHeaderField("Connection", "close");
    request.addHeaderField("Content-Length", String.valueOf(requestData.length));
    request.setHttpEntity(new ByteArrayEntity(requestData));
    request.setEnvelope(envelope);
}

From source file:ca.uhn.fhir.rest.client.apache.GZipContentInterceptor.java

@Override
public void interceptRequest(IHttpRequest theRequestInterface) {
    HttpRequestBase theRequest = ((ApacheHttpRequest) theRequestInterface).getApacheRequest();
    if (theRequest instanceof HttpEntityEnclosingRequest) {
        Header[] encodingHeaders = theRequest.getHeaders(Constants.HEADER_CONTENT_ENCODING);
        if (encodingHeaders == null || encodingHeaders.length == 0) {
            HttpEntityEnclosingRequest req = (HttpEntityEnclosingRequest) theRequest;

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            GZIPOutputStream gos;
            try {
                gos = new GZIPOutputStream(bos);
                req.getEntity().writeTo(gos);
                gos.finish();/*from  w w  w . ja v  a 2  s .c o m*/
            } catch (IOException e) {
                ourLog.warn("Failed to GZip outgoing content", e);
                return;
            }

            byte[] byteArray = bos.toByteArray();
            ByteArrayEntity newEntity = new ByteArrayEntity(byteArray);
            req.setEntity(newEntity);
            req.addHeader(Constants.HEADER_CONTENT_ENCODING, "gzip");
        }
    }

}

From source file:org.jwebsocket.sso.HTTPSupport.java

/**
 *
 * @param aURL//from  ww w. ja v  a2s  .c o m
 * @param aMethod
 * @param aHeaders
 * @param aPostBody
 * @param aTimeout
 * @return
 */
public static String request(String aURL, String aMethod, Map<String, String> aHeaders, String aPostBody,
        long aTimeout) {
    if (mLog.isDebugEnabled()) {
        mLog.debug("Requesting (" + aMethod + ") '" + aURL + "', timeout: " + aTimeout + "ms, Headers: "
                + aHeaders + ", Body: "
                + (null != aPostBody ? "'" + aPostBody.replace("\n", "\\n").replace("\r", "\\r") + "'"
                        : "[null]"));
    }
    String lResponse = "{\"code\": -1, \"msg\": \"undefined\"";
    try {
        KeyStore lTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        lTrustStore.load(null, null);
        // Trust own CA and all self-signed certs
        SSLContext lSSLContext = SSLContexts.custom()
                .loadTrustMaterial(lTrustStore, new TrustSelfSignedStrategy()).build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory lSSLFactory = new SSLConnectionSocketFactory(lSSLContext,
                new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        CloseableHttpClient lHTTPClient = HttpClients.custom().setSSLSocketFactory(lSSLFactory).build();
        HttpUriRequest lRequest;
        if ("POST".equals(aMethod)) {
            lRequest = new HttpPost(aURL);
            ((HttpPost) lRequest).setEntity(new ByteArrayEntity(aPostBody.getBytes("UTF-8")));
        } else {
            lRequest = new HttpGet(aURL);
        }
        for (Map.Entry<String, String> lEntry : aHeaders.entrySet()) {
            lRequest.setHeader(lEntry.getKey(), lEntry.getValue());
        }

        // System.out.println("Executing request " + lRequest.getRequestLine());
        // Create a custom response handler
        ResponseHandler<String> lResponseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse lResponse)
                    throws ClientProtocolException, IOException {
                int lStatus = lResponse.getStatusLine().getStatusCode();
                HttpEntity lEntity = lResponse.getEntity();
                return lEntity != null ? EntityUtils.toString(lEntity) : null;

                //               if (lStatus >= 200 && lStatus < 300) {
                //                  HttpEntity entity = lResponse.getEntity();
                //                  return entity != null ? EntityUtils.toString(entity) : null;
                //               } else {
                //                  throw new ClientProtocolException("Unexpected response status: " + lStatus);
                //               }
            }

        };
        long lStartedAt = System.currentTimeMillis();
        lResponse = lHTTPClient.execute(lRequest, lResponseHandler);
        if (mLog.isDebugEnabled()) {
            mLog.debug("Response (" + (System.currentTimeMillis() - lStartedAt) + "ms): '"
                    + lResponse.replace("\n", "\\n").replace("\r", "\\r") + "'");
        }
        return lResponse;
    } catch (Exception lEx) {
        String lMsg = "{\"code\": -1, \"msg\": \"" + lEx.getClass().getSimpleName() + " at http request: "
                + lEx.getMessage() + "\"}";
        mLog.error(lEx.getClass().getSimpleName() + ": " + lEx.getMessage() + ", returning: " + lMsg);
        lResponse = lMsg;
        return lResponse;
    }
}

From source file:com.digitalarx.android.syncadapter.ContactSyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {/*from   w ww  . j a va2 s.co m*/
    setAccount(account);
    setContentProviderClient(provider);
    Cursor c = getLocalContacts(false);
    if (c.moveToFirst()) {
        do {
            String lookup = c.getString(c.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
            String a = getAddressBookUri();
            String uri = a + lookup + ".vcf";
            FileInputStream f;
            try {
                f = getContactVcard(lookup);
                HttpPut query = new HttpPut(uri);
                byte[] b = new byte[f.available()];
                f.read(b);
                query.setEntity(new ByteArrayEntity(b));
                fireRawRequest(query);
            } catch (IOException e) {
                e.printStackTrace();
                return;
            } catch (OperationCanceledException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (AuthenticatorException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } while (c.moveToNext());
        // } while (c.moveToNext());
    }

}

From source file:org.vuphone.assassins.android.http.HTTPPoster.java

public static void doLandMineRemove(LandMine lm) {

    final HttpPost post = new HttpPost(VUphone.SERVER + PATH);
    post.addHeader("Content-Type", "application/x-www-form-urlencoded");

    StringBuffer params = new StringBuffer();
    params.append("type=landMineRemove&lat=" + lm.getLatitude() + "&lon=" + lm.getLongitude());

    Log.v(VUphone.tag, pre + "Created parameter string: " + params);
    post.setEntity(new ByteArrayEntity(params.toString().getBytes()));

    // Do it// w ww.  j a v  a 2  s .  c o  m
    Log.i(VUphone.tag, pre + "Executing post to " + VUphone.SERVER + PATH);

    HttpResponse resp = null;
    try {
        resp = c.execute(post);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        resp.getEntity().writeTo(bao);
        Log.d(VUphone.tag, pre + "Response from server: " + new String(bao.toByteArray()));
    } catch (ClientProtocolException e) {
        Log.e(VUphone.tag, pre + "ClientProtocolException executing post: " + e.getMessage());
    } catch (IOException e) {
        Log.e(VUphone.tag, pre + "IOException writing to ByteArrayOutputStream: " + e.getMessage());
    } catch (Exception e) {
        Log.e(VUphone.tag, pre + "Other Exception of type:" + e.getClass());
        Log.e(VUphone.tag, pre + "The message is: " + e.getMessage());
    }
}

From source file:com.lenovo.h2000.services.LicenseServiceImpl.java

@Override
public String upload(String filePath, Map<String, String> headers) throws Exception {
    _logger.info("calling LicenseServiceImpl.upload function");
    Map<String, String> params = new HashMap<String, String>();

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(
            HttpConfig.parseBaseUrl(headers) + "license/import" + "?" + TypeUtil.mapToString(params));// new HttpPost("http://localhost:3002/license/import");

    String responseBody = "";
    DataInputStream in = null;/*from   w w w  . j av  a2s  .co  m*/
    try {
        _logger.info("filePath" + filePath);
        File file = new File(filePath);
        in = new DataInputStream(new FileInputStream(filePath));
        byte[] bufferOut = new byte[(int) file.length()];

        int bytes = 0;
        int i = 0;
        int len = (int) (1024 > file.length() ? file.length() : 1024);
        while ((bytes = in.read(bufferOut, i, len)) > 0) {
            if (bytes < 1024)
                break;
            else {
                len = (int) (file.length() - bytes);
                i += bytes;
            }
        }

        ByteArrayEntity requestEntity = new ByteArrayEntity(bufferOut);
        requestEntity.setContentEncoding("UTF-8");
        requestEntity.setContentType("application/octet-stream");
        httpPost.setEntity(requestEntity);
        HttpResponse response = httpClient.execute(httpPost);
        response.setHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
        HttpEntity responseEntity = response.getEntity();
        responseBody = EntityUtils.toString(responseEntity);

        if (file.isFile() && file.exists()) {
            file.delete();
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
        _logger.error("throwing HttpClientUtil.doPost ClientProtocolException with " + e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        _logger.error("throwing HttpClientUtil.doPost IOException with " + e.getMessage());
    } finally {
        httpClient.close();
        if (in != null) {
            in.close();
        }
    }
    return responseBody;
}