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

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///from  ww w.  j  av a 2 s  .  com
@SuppressWarnings("deprecation")
/* protected */ HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws AuthFailureError, IOException {

    String url = request.getUrl();
    if (mUrlRewriter != null) {
        url = mUrlRewriter.rewriteUrl(url);
        if (url == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
    }
    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.getBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(url);
            //                    postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(url);
        }
    }
    case Method.GET:
        return new HttpGet(url);
    case Method.DELETE:
        return new HttpDelete(url);
    case Method.POST: {
        HttpPost postRequest = new HttpPost(url);
        //                postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(url);
        //                putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    case Method.HEAD:
        return new HttpHead(url);
    case Method.OPTIONS:
        return new HttpOptions(url);
    case Method.TRACE:
        return new HttpTrace(url);
    case Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(url);
        //                patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:com.hp.octane.integrations.services.rest.SSCRestClientImpl.java

private AuthToken.AuthTokenData sendReqAuth(SSCProjectConfiguration sscProjectConfiguration) {
    //"/{SSC Server Context}/api/v1"
    //String url = "http://" + serverURL + "/ssc/api/v1/projects?q=id:2743&fulltextsearch=true";
    String url = sscProjectConfiguration.getSSCUrl() + "/api/v1/tokens";
    HttpPost request = new HttpPost(url);
    request.addHeader("Authorization", sscProjectConfiguration.getSSCBaseAuthToken());
    request.addHeader("Accept", "application/json");
    request.addHeader("Host", getNetHost(sscProjectConfiguration.getSSCUrl()));
    request.addHeader("Content-Type", "application/json;charset=UTF-8");

    String body = "{\"type\": \"UnifiedLoginToken\"}";
    CloseableHttpResponse response = null;
    try {// www . j  av a  2  s  .c om
        HttpEntity entity = new ByteArrayEntity(body.getBytes(StandardCharsets.UTF_8));
        request.setEntity(entity);
        response = httpClient.execute(request);
        if (succeeded(response.getStatusLine().getStatusCode())) {
            String toString = CIPluginSDKUtils.inputStreamToUTF8String(response.getEntity().getContent());
            AuthToken authToken = new ObjectMapper().readValue(toString,
                    TypeFactory.defaultInstance().constructType(AuthToken.class));
            return authToken.getData();
        } else {
            throw new PermanentException(
                    "Couldn't Authenticate SSC user, need to check SSC configuration in Octane plugin");
        }
    } catch (Throwable t) {
        throw new PermanentException(t);
    } finally {
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
            HttpClientUtils.closeQuietly(response);
        }
    }
}

From source file:org.bedework.util.http.HttpUtil.java

/** Send content
 *
 * @param content the content as bytes/*  w  w  w.  j  a  v a  2 s .com*/
 * @param contentType its type
 * @throws HttpException if not entity enclosing request
 */
public static void setContent(final HttpRequestBase req, final byte[] content, final String contentType)
        throws HttpException {
    if (content == null) {
        return;
    }

    if (!(req instanceof HttpEntityEnclosingRequestBase)) {
        throw new HttpException("Invalid operation for method " + req.getMethod());
    }

    final HttpEntityEnclosingRequestBase eem = (HttpEntityEnclosingRequestBase) req;

    final ByteArrayEntity entity = new ByteArrayEntity(content);
    entity.setContentType(contentType);
    eem.setEntity(entity);
}

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

/**
 * request??/*  w ww  .  j  a  v  a 2s .  c  om*/
 * @param httpRequest
 * @param request
 * @throws AuthFailureError
 */
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request)
        throws AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        HttpEntity entity = new ByteArrayEntity(body);
        httpRequest.setEntity(entity);
    }
}

From source file:com.spotify.asyncdatastoreclient.Datastore.java

private HttpResponse executeRequest(final String method, final ProtoHttpContent payload)
        throws DatastoreException {
    int maxRetries = config.getRequestRetry();
    int i = 0;//from w  ww .j  ava2  s.c  om
    ByteArrayEntity entity = new ByteArrayEntity(payload.getMessage().toByteArray());
    while (i++ <= maxRetries) {
        try {
            HttpPost httpPost = new HttpPost(prefixUri + method);
            httpPost.addHeader("Authorization", "Bearer " + accessToken);
            httpPost.addHeader("Content-Type", "application/x-protobuf");
            httpPost.addHeader("User-Agent", USER_AGENT);
            httpPost.addHeader("Accept-Encoding", "gzip");

            httpPost.setEntity(entity);

            HttpResponse httpResponse = client.execute(httpPost, null).get();
            checkSuccessful(httpResponse);

            return httpResponse;
        } catch (Exception e) {
            if (i == maxRetries) {
                throw new DatastoreException(e);
            }
        }
    }
    // Should never reach here
    throw new DatastoreException("");
}

From source file:com.base.net.volley.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *//*from w ww . j a  v  a 2 s . com*/
@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());
        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.");
    }
}

From source file:com.subgraph.vega.internal.http.requests.EngineHttpResponse.java

@Override
public boolean lockResponseEntity() {
    final HttpEntity entity = rawResponse.getEntity();
    if (entity == null)
        return false;
    try {/*from   w w  w . j a v  a  2 s. co  m*/
        final ByteArrayEntity newEntity = new ByteArrayEntity(EntityUtils.toByteArray(entity));
        newEntity.setContentType(entity.getContentType());
        newEntity.setContentEncoding(entity.getContentEncoding());
        rawResponse.setEntity(newEntity);
        EntityUtils.consume(entity);
        return true;
    } catch (IOException e) {
        logger.warning("Error loading entity for " + getRequestUri().toString() + " : " + e.getMessage());
        return false;
    }
}

From source file:de.ub0r.android.websms.connector.freenet.ConnectorFreenet.java

/**
 * send xml command send to freenet XML sms connector and return XML
 * response/*from w  w  w  . j av a 2 s . c o  m*/
 * 
 * @param context
 *            sms connector context
 * @param xml
 *            command to send to freenet XML sms connector
 * @return String contaning XML response
 */
private String sendXml(final Context context, final String xml) {
    String resXml = null;
    try {
        // POST UTF-8 xml command to server
        final HttpPost req = new HttpPost(URL_EMO);
        req.setHeader("content-type", "text/xml");
        final byte[] bytes = xml.getBytes("utf-8");
        req.setEntity(new ByteArrayEntity(bytes));
        final HttpResponse response = this.client.execute(req);
        // check server status
        final int resp = response.getStatusLine().getStatusCode();
        if (resp != HttpURLConnection.HTTP_OK) {
            throw new WebSMSException(context, R.string.error_http, " " + resp);
        }
        // parse XML response into HashMap
        final InputStream in = response.getEntity().getContent();
        final int cnt = in.read(this.httpBuffer);
        if (cnt > 0) {
            resXml = new String(this.httpBuffer, 0, cnt, "utf-8");
        }
        if (null == resXml) {
            throw new WebSMSException(context, R.string.error_http, "no XML from server");
        }
        // else {
        // Log.d(TAG, resXml);
        // }
    } catch (Exception e) {
        Log.e(TAG, "sendXml", e);
        throw new WebSMSException(e.getMessage());
    }
    return resXml;
}

From source file:org.soyatec.windowsazure.table.internal.CloudTableRest.java

@Override
public boolean createTable() {
    boolean result = (Boolean) getRetryPolicy().execute(new Callable<Boolean>() {
        public Boolean call() throws Exception {

            ResourceUriComponents uriComponents = new ResourceUriComponents(getAccountName(),
                    TableStorageConstants.TablesName, null);

            URI uri = HttpUtilities.createRequestUri(getBaseUri(), isUsePathStyleUris(), getAccountName(),
                    TableStorageConstants.TablesName, null, null, new NameValueCollection(), uriComponents);
            HttpRequest request = HttpUtilities.createHttpRequest(uri, HttpMethod.Post);
            request.addHeader(HeaderNames.ContentType, TableStorageConstants.AtomXml);
            request.addHeader(HeaderNames.Date, Utilities.getUTCTime());

            String atom = AtomUtil.createTableXml(tableName);
            ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(atom.getBytes()));
            credentials.signRequestForSharedKeyLite(request, uriComponents);
            HttpWebResponse response = HttpUtilities.getResponse(request);
            if (response.getStatusCode() == HttpStatus.SC_CREATED) {
                response.close();//from   w  ww .  j ava2s .c o m
                return true;
            } else if (response.getStatusCode() == HttpStatus.SC_CONFLICT) {
                lastStatus = HttpUtilities.convertStreamToString(response.getStream());
                response.close();
                return false;
            } else {
                HttpUtilities.processUnexpectedStatusCode(response);
            }
            return false;
        }
    });
    return result;
}