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.yoelnunez.mobilefirst.analytics.AnalyticsAPI.java

public static void send() {
    JSONArray payload = new JSONArray();

    for (Map.Entry<JSONObject, JSONArray> set : logs.entrySet()) {
        JSONObject doc = new JSONObject();
        doc.put("worklight_data", set.getKey());
        doc.put("_type", "RawMfpAppLogs");
        doc.put("client_logs", set.getValue());

        payload.put(doc);//from   w  w w.ja  v a2  s  .  c o  m
    }

    String credentials = serverContext.getUsername() + ":" + serverContext.getPassword();

    HttpPost post = new HttpPost(serverContext.getEndpoint());
    post.addHeader("Content-Type", "application/json");
    post.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(credentials.getBytes())));

    HttpEntity entity = new ByteArrayEntity(payload.toString().getBytes());
    post.setEntity(entity);

    try {
        httpClient.execute(post);

        logs.clear();
    } catch (IOException ignored) {
    }
}

From source file:ee.ioc.phon.netspeechapi.Recognizer.java

private String postByteArray(byte[] bytes, String mime, int rate) throws ClientProtocolException, IOException {
    HttpPost post = new HttpPost(mWsUrl);
    setUserAgent(post);//from  w  w w. ja  v a2s.  com

    ByteArrayEntity entity = new ByteArrayEntity(bytes);
    entity.setContentType(mime + "; rate=" + rate);
    post.setEntity(entity);

    return Utils.getResponseEntityAsString(post);
}

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

public static int sendPUT(String endpoint, String content, Map<String, String> headers) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPut httpPut = new HttpPut(endpoint);
    for (String headerType : headers.keySet()) {
        httpPut.setHeader(headerType, headers.get(headerType));
    }/*from ww w . ja  v  a2  s  .c o m*/
    if (null != content) {
        HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
        if (headers.get("Content-Type") == null) {
            httpPut.setHeader("Content-Type", "application/json");
        }
        httpPut.setEntity(httpEntity);
    }
    HttpResponse httpResponse = httpClient.execute(httpPut);
    return httpResponse.getStatusLine().getStatusCode();
}

From source file:com.github.ljtfreitas.restify.http.client.request.apache.httpclient.ApacheHttpClientRequest.java

@Override
public HttpResponseMessage execute() throws RestifyHttpException {
    headers.all().forEach(h -> httpRequest.addHeader(h.name(), h.value()));

    if (httpRequest instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) httpRequest;
        HttpEntity requestEntity = new ByteArrayEntity(byteArrayOutputStream.toByteArray());
        entityEnclosingRequest.setEntity(requestEntity);
    }//from   w ww. j  a va2 s  .  c om

    try {
        HttpResponse httpResponse = httpClient.execute(httpRequest, httpContext);

        return responseOf(httpResponse);

    } catch (IOException e) {
        throw new RestifyHttpException(e);
    }

}

From source file:edu.cmu.cylab.starslinger.exchange.WebEngine.java

private byte[] doPost(String uri, byte[] requestBody) throws ExchangeException {
    mCancelable = false;//from  w ww  . j a  v a  2s  .  co m

    // sets up parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");
    params.setBooleanParameter("http.protocol.expect-continue", false);

    if (mHttpClient == null) {
        mHttpClient = new CheckedHttpClient(params, mCtx);
    }
    HttpPost httppost = new HttpPost(uri);
    BasicResponseHandler responseHandler = new BasicResponseHandler();
    byte[] reqData = null;
    HttpResponse response = null;
    long startTime = SystemClock.elapsedRealtime();
    int statCode = 0;
    String statMsg = "";
    String error = "";

    try {
        // Execute HTTP Post Request
        httppost.addHeader("Content-Type", "application/octet-stream");
        httppost.setEntity(new ByteArrayEntity(requestBody));
        response = mHttpClient.execute(httppost);
        reqData = responseHandler.handleResponse(response).getBytes("8859_1");

    } catch (UnsupportedEncodingException e) {
        error = e.getLocalizedMessage() + " (" + e.getClass().getSimpleName() + ")";
    } catch (HttpResponseException e) {
        // this subclass of java.io.IOException contains useful data for
        // users, do not swallow, handle properly
        e.printStackTrace();
        statCode = e.getStatusCode();
        statMsg = e.getLocalizedMessage();
        error = (String.format(mCtx.getString(R.string.error_HttpCode), statCode) + ", \'" + statMsg + "\'");
    } catch (java.io.IOException e) {
        // just show a simple Internet connection error, so as not to
        // confuse users
        e.printStackTrace();
        error = mCtx.getString(R.string.error_CorrectYourInternetConnection);
    } catch (RuntimeException e) {
        error = e.getLocalizedMessage() + " (" + e.getClass().getSimpleName() + ")";
    } catch (OutOfMemoryError e) {
        error = mCtx.getString(R.string.error_OutOfMemoryError);
    } finally {
        long msDelta = SystemClock.elapsedRealtime() - startTime;
        if (response != null) {
            StatusLine status = response.getStatusLine();
            if (status != null) {
                statCode = status.getStatusCode();
                statMsg = status.getReasonPhrase();
            }
        }
        Log.d(TAG, uri + ", " + requestBody.length + "b sent, " + (reqData != null ? reqData.length : 0)
                + "b recv, " + statCode + " code, " + msDelta + "ms");
    }

    if (!TextUtils.isEmpty(error) || reqData == null) {
        throw new ExchangeException(error);
    }
    return reqData;
}

From source file:org.openqa.selenium.remote.internal.ApacheHttpClient.java

@Override
public HttpResponse execute(HttpRequest request, boolean followRedirects) throws IOException {
    HttpContext context = createContext();

    String requestUrl = url.toExternalForm().replaceAll("/$", "") + request.getUri();
    HttpUriRequest httpMethod = createHttpUriRequest(request.getMethod(), requestUrl);
    for (String name : request.getHeaderNames()) {
        // Skip content length as it is implicitly set when the message entity is set below.
        if (!"Content-Length".equalsIgnoreCase(name)) {
            for (String value : request.getHeaders(name)) {
                httpMethod.addHeader(name, value);
            }// w  w  w.j av a2 s .  co m
        }
    }

    if (httpMethod instanceof HttpPost) {
        ((HttpPost) httpMethod).setEntity(new ByteArrayEntity(request.getContent()));
    }

    org.apache.http.HttpResponse response = fallBackExecute(context, httpMethod);
    if (followRedirects) {
        response = followRedirects(client, context, response, /* redirect count */0);
    }
    return createResponse(response, context);
}

From source file:org.wso2.identity.sample.webapp.OAuthTokenGenerator.java

private String sendPost(String str, String type) throws Exception {
    PlatformUtils.setKeyStoreProperties();
    PlatformUtils.setKeyStoreParams();//from   w  w  w  . ja  va2  s  .  com
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(oauthTokenEndpoint);

    // add header
    post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    post.setHeader("Authorization", encodedBasicHeader);

    String content = null;

    if (type.equals("generate")) {
        content = "grant_type=urn:ietf:params:oauth:grant-type:saml2-bearer&assertion=" + str
                + "&scope=PRODUCTION";
        System.out.println("#################### SAML ASSERTION ########### ");
        System.out.println(str);
    } else if (type.equals("refresh")) {
        content = "grant_type=refresh_token&refresh_token=" + str + "&scope=PRODUCTION";
    }

    HttpEntity entity = new ByteArrayEntity(content.getBytes("UTF-8"));
    post.setEntity(entity);
    HttpResponse response = client.execute(post);
    String result = EntityUtils.toString(response.getEntity());

    return result;
}

From source file:com.microsoft.office365.meetingmgr.HttpHelperBase.java

private <TBody, TResult> TResult doHttp(HttpRequestBaseHC4 httpRequest, TBody body, Class<TResult> clazz) {
    String requestBody;/*from   www .  jav a2 s .  c  o  m*/
    String requestString;

    if (body == null) {
        requestString = requestBody = null;
    } else if (body instanceof String) {
        requestString = requestBody = (String) body;
        httpRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
    } else {
        requestBody = mJson.serialize(body);
        requestString = mJson.prettyPrint(body);
        httpRequest.setHeader("Content-Type", "application/json");
    }

    traceRequest(httpRequest, requestString);

    try {
        if (requestBody != null) {
            HttpEntity entityBody = new ByteArrayEntity(requestBody.getBytes(CHARSET_NAME));
            ((HttpEntityEnclosingRequestBaseHC4) httpRequest).setEntity(entityBody);
        }

        try (CloseableHttpResponse result = executeRequest(httpRequest)) {
            return getResult(result, clazz);
        }
    } catch (IOException | ExecutionException | InterruptedException e) {
        ErrorLogger.log(e);
    }
    return null;
}

From source file:wsattacker.plugin.intelligentdos.requestSender.Http4RequestSenderImpl.java

public String sendRequestHttpClient(RequestObject requestObject) {
    String strUrl = requestObject.getEndpoint();
    String strXml = requestObject.getRequestContent();

    StringBuilder result = new StringBuilder();
    BufferedReader rd = null;//  w ww  .  j  ava 2  s.  c  om
    try {
        URL url = new URL(strUrl);
        String protocol = url.getProtocol();

        HttpClient client;
        if (protocol.equalsIgnoreCase("https")) {
            SSLSocketFactory sf = get();
            Scheme httpsScheme = new Scheme("https", url.getPort(), sf);
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(httpsScheme);

            // apache HttpClient version >4.2 should use
            // BasicClientConnectionManager
            ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);

            client = new DefaultHttpClient(cm);
        } else {
            client = new DefaultHttpClient();
        }

        setParamsToClient(client);

        HttpPost post = new HttpPost(strUrl);
        setHeader(requestObject, post);

        ByteArrayEntity entity = new ByteArrayEntity(strXml.getBytes("UTF-8")) {
            @Override
            public void writeTo(OutputStream outstream) throws IOException {
                super.writeTo(outstream);
                sendLastByte = System.nanoTime();
            }
        };

        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        receiveFirstByte = System.nanoTime();

        rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), Charset.defaultCharset()));

        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (IOException e) {
        return e.getMessage();
    } catch (RuntimeException e) {
        return e.getMessage();
    } finally {
        if (rd != null) {
            try {
                rd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return result.toString();
}

From source file:neal.http.impl.httpstack.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///from w w w  .  java  2s  .  c o m
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws HttpErrorCollection.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());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    case Method.HEAD:
        return new HttpHead(request.getUrl());
    case Method.OPTIONS:
        return new HttpOptions(request.getUrl());
    case Method.TRACE:
        return new HttpTrace(request.getUrl());
    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.");
    }
}