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.falcon.orca.actors.Generator.java

private HttpUriRequest prepareRequest() throws URISyntaxException, JsonProcessingException {
    HttpUriRequest request;/*  w ww.j a v  a 2 s.  co  m*/
    switch (method) {
    case POST: {
        String postUrl = isUrlDynamic ? dataStore.fillURLWithData() : url;
        AbstractHttpEntity postData;
        try {
            postData = isBodyDynamic
                    ? new StringEntity(dataStore.fillTemplateWithData(), StandardCharsets.UTF_8)
                    : new ByteArrayEntity(staticRequestData == null ? new byte[0] : staticRequestData);
        } catch (IllegalArgumentException ile) {
            postData = new ByteArrayEntity(new byte[0]);
            log.error("Post body is null, sending blank.");
        }
        request = new HttpPost(postUrl);
        ((HttpPost) request).setEntity(postData);
        break;
    }
    case GET: {
        String getUrl = isUrlDynamic ? dataStore.fillURLWithData() : url;
        request = new HttpGet(getUrl);
        break;
    }
    case PUT: {
        String putUrl = isUrlDynamic ? dataStore.fillURLWithData() : url;
        AbstractHttpEntity putData;
        try {
            putData = isBodyDynamic ? new StringEntity(dataStore.fillTemplateWithData(), StandardCharsets.UTF_8)
                    : new ByteArrayEntity(staticRequestData == null ? new byte[0] : staticRequestData);
        } catch (IllegalArgumentException ile) {
            putData = new ByteArrayEntity(new byte[0]);
            log.error("Post body is null, sending blank.");
        }
        request = new HttpPut(putUrl);
        ((HttpPut) request).setEntity(putData);
        break;
    }
    case DELETE: {
        String deleteUrl = isUrlDynamic ? dataStore.fillURLWithData() : url;
        request = new HttpDelete(deleteUrl);
        break;
    }
    case OPTIONS: {
        String optionsUrl = isUrlDynamic ? dataStore.fillURLWithData() : url;
        request = new HttpOptions(optionsUrl);
        break;
    }
    case HEAD: {
        String headUrl = isUrlDynamic ? dataStore.fillURLWithData() : url;
        request = new HttpHead(headUrl);
        break;
    }
    default:
        throw new URISyntaxException(url + ":" + method,
                "Wrong method supplied, available methods are POST, " + "GET, PUT, DELETE, HEAD, OPTIONS");
    }
    if (headers != null) {
        headers.forEach(request::addHeader);
    }
    return request;
}

From source file:br.com.anteros.android.synchronism.communication.HttpConnectionClient.java

public MobileResponse sendReceiveData(MobileRequest mobileRequest) {
    sessionId = HttpConnectionSession.getInstance().getSessionId();

    add(mobileRequest.getFormattedHeader(), mobileRequest.getFormatedActions());
    MobileResponse mobileResponse = new MobileResponse();
    try {//ww  w.  j  a  va2 s .  com
        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onWaitServer();
        }

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onStatusConnectionServer("Conectando Servidor...");
        }

        /*
         * Define url e estabelece conexo
         */

        HttpPost httpPost = new HttpPost(url);

        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is
        // established.
        // The default value is zero, that means the timeout is not used.
        HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_CONNECTION);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_SOCKET);

        if (httpClient == null)
            httpClient = new DefaultHttpClient(httpParameters);

        //

        /*
         * Setar o cookie da sesso
         */
        if ((sessionId != null) && (!"".equals(sessionId))) {
            httpPost.setHeader("Cookie", "JSESSIONID=" + sessionId);
        }
        httpPost.setHeader("User-Agent", "Android");
        httpPost.setHeader("Accept-Encoding", "gzip");

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onStatusConnectionServer("Enviando requisio...");
        }

        //
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(baos);
        //

        /*
         * Escrever no output
         */
        out.writeInt(numOption);
        String aux[];
        for (int i = 0; i < opPOST.size(); i++) {
            aux = (String[]) opPOST.get(i);

            out.writeUTF(aux[0]);

            byte[] b = aux[1].getBytes();
            out.writeInt(b.length);
            out.write(b);

            aux = null;
        }
        out.flush();

        ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray());
        entity.setContentEncoding("UTF-8");
        httpPost.setEntity(entity);
        httpPost.addHeader("Connection", "Keep-Alive");
        httpPost.addHeader("Keep-Alive", "timeout=120000");

        out.close();
        //

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onStatusConnectionServer("Recebendo dados...");
        }

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onDebugMessage("Recebendo dados conexo");
        }

        /*
         * Aguardar resposta
         */
        HttpResponse httpResponse = httpClient.execute(httpPost);
        List result = null;
        StatusLine statusLine = httpResponse.getStatusLine();
        int code = statusLine.getStatusCode();
        if (code != 200) {
            String msg = "Erro RECEBENDO resposta do Servidor " + url + " - Cdigo do Erro HTTP " + code + "-"
                    + statusLine.getReasonPhrase();
            mobileResponse.setStatus(msg);
        } else {
            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onStatusConnectionServer("Resposta OK !");
            }

            /*
             * Ler cookie
             */
            String tmpSessionId = null;

            for (Cookie c : httpClient.getCookieStore().getCookies()) {
                if ("JSESSIONID".equals(c.getName())) {
                    tmpSessionId = c.getValue();
                }
            }

            if (tmpSessionId != null) {
                sessionId = tmpSessionId;
                HttpConnectionSession.getInstance().setSessionId(sessionId);
            }
            //

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onStatusConnectionServer("Lendo dados...");
            }

            /*
             * Le os dados
             */
            HttpEntity entityResponse = httpResponse.getEntity();
            InputStream in = AndroidHttpClient.getUngzippedContent(entityResponse);

            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));

            String content = null;

            content = reader.readLine();
            String line = null;
            while ((line = reader.readLine()) != null) {
                content += line;
            }
            line = "";

            reader.close();
            reader = null;
            in.close();
            in = null;
            entityResponse.consumeContent();
            entityResponse = null;
            //

            StringTokenizer messagePart = new StringTokenizer(content, "#");
            content = null;

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onDebugMessage("RECEBEU dados conexo");
            }

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onStatusConnectionServer("Processando resposta... ");
            }

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onDebugMessage("Converteu string dados conexo");
            }

            while (messagePart.hasMoreTokens()) {
                String resultData = messagePart.nextToken();
                resultData = resultData.substring(resultData.indexOf("*") + 1, resultData.length());
                if (result == null)
                    result = formatData(resultData);
                else
                    result.addAll(formatData(resultData));
            }
            messagePart = null;
        }

        if (result != null) {
            mobileResponse.setFormattedParameters(result);
            result.clear();
            result = null;
        }

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onEndServer();
        }

    } catch (SocketTimeoutException exTimeout) {
        exTimeout.printStackTrace();
        wrapException(mobileResponse, "No foi possvel CONECTAR ao Servidor " + url
                + ". Verifique sua conexo e se o servidor est em funcionamento.");
    } catch (Exception e) {
        e.printStackTrace();
        if ((e.getMessage() + "").contains("unreachable"))
            wrapException(mobileResponse,
                    "Voc est sem acesso a internet. Verifique sua conexo. No foi possvel conectar ao servidor  "
                            + url);
        else
            wrapException(mobileResponse,
                    "No foi possivel CONECTAR ao Servidor " + url + " " + e.getMessage());
    }
    return mobileResponse;
}

From source file:com.jzboy.couchdb.http.CouchHttpClient.java

/**
 * Sends a PUT request to the specified CouchDB endpoint.
 * Use this version to add attachments.// w ww  .j a  v  a 2s.co m
 * @param uri      CouchDB API endpoint
 * @param data      request data
 * @param mimeType   the MIME type of the data. This is added as a Content-Type header to the request
 * @return the JSON tree parsed form the response body
 * @throws IOException      if the HttpClient throws an IOException
 * @throws CouchDBException   if CouchDB returns an error - response code >= 300. The response details are
 * encapsulated in the exception.
 */
public JsonNode put(URI uri, byte[] data, String mimeType) throws IOException, CouchDBException {
    HttpPut req = new HttpPut(uri);
    req.setEntity(new ByteArrayEntity(data));
    req.addHeader("Content-Type", mimeType);
    return execRequest(req);
}

From source file:org.mobicents.xcap.client.impl.XcapClientImpl.java

private void setRequestEntity(HttpPut request, byte[] content, String mimetype)
        throws UnsupportedEncodingException {
    request.setHeader(XcapConstant.HEADER_CONTENT_TYPE, mimetype);
    request.setEntity(new ByteArrayEntity(content));
}

From source file:com.eviware.soapui.testondemand.TestOnDemandCaller.java

@NonNull
public String sendTestCase(@NonNull WsdlTestCase testCase, @NonNull Location location) throws Exception {

    final ExtendedPostMethod post = new ExtendedPostMethod();
    post.setURI(new URI(UPLOAD_URI));

    String locationCode = location.getCode();

    String encodedTestSuiteName = getBase64EncodedString(testCase.getTestSuite().getName().getBytes());
    String encodedTestCaseName = getBase64EncodedString(testCase.getName().getBytes());

    File tempProjectFile = saveTemporaryProject(testCase.getTestSuite().getProject());
    byte[] projectFileData = getBytes(tempProjectFile.getAbsolutePath());
    byte[] zipedProjectFileData = zipBytes(testCase.getTestSuite().getProject().getName(), projectFileData);
    String encodedZipedProjectFile = getBase64EncodedString(zipedProjectFileData);

    String projectPassword = testCase.getTestSuite().getProject().getShadowPassword();
    String encodedProjectPassword = getBase64EncodedString(Strings.nullToEmpty(projectPassword).getBytes());

    String keystoreFilePath = SoapUI.getSettings().getString(SSLSettings.KEYSTORE, "");
    byte[] keystoreFileData = getBytes(keystoreFilePath);
    String encodedKeystoreFile = getBase64EncodedString(keystoreFileData);

    String encodedKeystorePassword = getBase64EncodedString(
            SoapUI.getSettings().getString(SSLSettings.KEYSTORE_PASSWORD, "").getBytes());

    String requestContent = generateUploadRequestXML(locationCode, encodedTestSuiteName, encodedTestCaseName,
            encodedZipedProjectFile, encodedProjectPassword, encodedKeystoreFile, encodedKeystorePassword);

    byte[] compressedRequestContent = CompressionSupport.compress(CompressionSupport.ALG_GZIP,
            requestContent.getBytes());/*w w w.j a va 2s.  c  om*/
    post.setEntity(new ByteArrayEntity(compressedRequestContent));

    Document responseDocument = makeCall(UPLOAD_URI, requestContent);
    String redirectURL = (String) xpath.evaluate(REDIRECT_URL_XPATH_EXPRESSION, responseDocument,
            XPathConstants.STRING);

    if (Strings.isNullOrEmpty(redirectURL)) {
        throw new RuntimeException("The RedirectURL element is missing in the response message");
    }
    return redirectURL;
}

From source file:com.comcast.csv.drivethru.api.HTTPRequestManager.java

/**
 * Sends request with data and returns {@link ResponseContainer} object containing response's status code and body.
 * @param client HttpClient use to send request
 * @param request Http request object to be sent out
 * @return {@link ResponseContainer} with response data
 * @throws IOException When there's an error sending out request
 *///  w w  w .j  a  va2s  .c  o  m
private ResponseContainer sendRequestWithData(CloseableHttpClient client, HttpUriRequest request)
        throws IOException {
    HttpEntityEnclosingRequestBase httpMethod = (HttpEntityEnclosingRequestBase) request;
    HttpEntity entity = new ByteArrayEntity(mData);

    httpMethod.setEntity(entity);

    return sendRequest(client, httpMethod);
}

From source file:com.intel.cosbench.client.amplistor.AmpliClient.java

public String StoreObject(byte[] data, String ampliNamespace, String ampliFilename)
        throws IOException, HttpException, AmpliException {
    // int len = data.length;
    HttpPut method = null;/*from   w  w w.j  av a2  s.co m*/
    String storageUrl = "http://" + this.host + ":" + this.port + nsRoot;
    method = HttpClientUtil.makeHttpPut(storageUrl + "/" + HttpClientUtil.encodeURL(ampliNamespace) + "/"
            + HttpClientUtil.encodeURL(ampliFilename));

    method.setHeader("Content-Type", "application/octet-stream");

    HttpResponse response = null;
    try {
        method.setEntity(new ByteArrayEntity(data));
        response = client.execute(method);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            return response.getFirstHeader("ETag").getValue();
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return response.getFirstHeader("ETag").getValue();
        } else {
            throw new AmpliException(ampliNamespace + "/" + ampliFilename + ": " + response.getStatusLine(),
                    response.getAllHeaders(), response.getStatusLine());
        }
    } finally {
        if (response != null)
            EntityUtils.consume(response.getEntity());
    }

}

From source file:com.couchbase.capi.TestCAPI.java

public void testBulkDocsDoesNotExist() throws Exception {
    HttpClient client = getClient();//from   ww w.j a va 2s.com

    HttpPost request = new HttpPost(String.format("http://localhost:%d/doesnotexist/_bulk_docs", port));

    Map<String, Object> doc = new HashMap<String, Object>();
    doc.put("_id", "abcdef");
    doc.put("_rev", "1-xyz");

    Map<String, Object> doc2 = new HashMap<String, Object>();
    doc2.put("_id", "ghijkl");
    doc2.put("_rev", "1-pdr");

    List<Object> docs = new ArrayList<Object>();
    docs.add(doc);
    docs.add(doc2);

    Map<String, Object> bulkDocs = new HashMap<String, Object>();
    bulkDocs.put("docs", docs);

    request.setEntity(new ByteArrayEntity(mapper.writeValueAsBytes(bulkDocs)));
    HttpResponse response = client.execute(request);

    Assert.assertEquals(404, response.getStatusLine().getStatusCode());
}

From source file:com.xiaomi.infra.galaxy.sds.client.SdsTHttpClient.java

private void flushUsingHttpClient() throws TTransportException {
    if (null == this.client) {
        throw new TTransportException("Null HttpClient, aborting.");
    }//  w w w . ja  va 2 s  .com

    // Extract request and reset buffer
    byte[] data = requestBuffer_.toByteArray();
    requestBuffer_.reset();

    HttpPost post = null;

    InputStream is = null;

    try {
        // Set request to path + query string
        post = new HttpPost(this.url_.getFile());

        //
        // Headers are added to the HttpPost instance, not
        // to HttpClient.
        //
        setHeaders(post, data);

        post.setEntity(new ByteArrayEntity(data));

        HttpResponse response = this.client.execute(this.host, post);
        int responseCode = response.getStatusLine().getStatusCode();
        String reasonPhrase = response.getStatusLine().getReasonPhrase();

        //
        // Retrieve the inputstream BEFORE checking the status code so
        // resources get freed in the finally clause.
        //

        is = response.getEntity().getContent();

        if (responseCode != HttpStatus.SC_OK) {
            adjustClock(response, responseCode);
            throw new HttpTTransportException(responseCode, reasonPhrase);
        }

        // Read the responses into a byte array so we can release the connection
        // early. This implies that the whole content will have to be read in
        // memory, and that momentarily we might use up twice the memory (while the
        // thrift struct is being read up the chain).
        // Proceeding differently might lead to exhaustion of connections and thus
        // to app failure.

        byte[] buf = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int len = 0;
        do {
            len = is.read(buf);
            if (len > 0) {
                baos.write(buf, 0, len);
            }
        } while (-1 != len);

        try {
            // Indicate we're done with the content.
            consume(response.getEntity());
        } catch (IOException ioe) {
            // We ignore this exception, it might only mean the server has no
            // keep-alive capability.
        }

        inputStream_ = new ByteArrayInputStream(baos.toByteArray());
    } catch (IOException ioe) {
        // Abort method so the connection gets released back to the connection manager
        if (null != post) {
            post.abort();
        }
        throw new TTransportException(ioe);
    } finally {
        if (null != is) {
            // Close the entity's input stream, this will release the underlying connection
            try {
                is.close();
            } catch (IOException ioe) {
                throw new TTransportException(ioe);
            }
        }
    }
}