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:it.unicaradio.android.utils.NetworkUtils.java

public static byte[] httpPost(String url, byte[] postData, String contentType)
        throws ClientProtocolException, IOException, HttpException {
    HttpParams httpParams = new BasicHttpParams();

    HttpPost post = new HttpPost(url);
    post.setEntity(new ByteArrayEntity(postData));
    post.addHeader("Content-Type", contentType);

    HttpClient client = new DefaultHttpClient(httpParams);
    HttpResponse response = client.execute(post);

    HttpEntity httpEntity = response.getEntity();
    if (httpEntity == null) {
        throw new HttpException("No answer from server.");
    }//  w  w  w .  ja v  a2  s.c  o m

    return EntityUtils.toByteArray(httpEntity);
}

From source file:com.excilys.sugadroid.services.impl.ksoap2.HttpClientTransportAndroid.java

@Override
public void call(String soapAction, SoapEnvelope envelope) throws IOException, XmlPullParserException {
    if (soapAction == null) {
        soapAction = "\"\"";
    }/* w w  w  .j av a 2  s.  c  om*/

    byte[] requestData = createRequestData(envelope);

    requestDump = debug ? new String(requestData) : null;
    responseDump = null;

    HttpPost method = new HttpPost(url);

    method.addHeader("User-Agent", "kSOAP/2.0-Excilys");
    method.addHeader("SOAPAction", soapAction);
    method.addHeader("Content-Type", "text/xml");

    HttpEntity entity = new ByteArrayEntity(requestData);

    method.setEntity(entity);

    HttpResponse response = httpClient.execute(method);

    InputStream inputStream = response.getEntity().getContent();

    if (debug) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[256];
        while (true) {
            int rd = inputStream.read(buf, 0, 256);
            if (rd == -1) {
                break;
            }
            bos.write(buf, 0, rd);
        }
        bos.flush();
        buf = bos.toByteArray();
        responseDump = new String(buf);
        inputStream.close();
        inputStream = new ByteArrayInputStream(buf);
    }

    parseResponse(envelope, inputStream);

    inputStream.close();

}

From source file:org.fcrepo.camel.FcrepoClientErrorTest.java

@Test
public void testGet() throws IOException, FcrepoOperationFailedException {
    final int status = 100;
    final URI uri = create(baseUrl);
    final ByteArrayEntity entity = new ByteArrayEntity(rdfXml.getBytes());

    entity.setContentType(RDF_XML);//from ww  w .  j ava2s.  c om
    doSetupMockRequest(RDF_XML, entity, status);

    final FcrepoResponse response = testClient.get(uri, RDF_XML, null);

    assertEquals(response.getUrl(), uri);
    assertEquals(response.getStatusCode(), status);
    assertEquals(response.getContentType(), RDF_XML);
    assertEquals(response.getLocation(), null);
    assertEquals(IOUtils.toString(response.getBody()), rdfXml);
}

From source file:org.opennms.smoketest.AlarmsPageIT.java

@Before
public void createAlarm() throws Exception {
    final EventBuilder builder = new EventBuilder(EventConstants.IMPORT_FAILED_UEI, "AlarmsPageTest");
    builder.setParam("importResource", "foo");
    final CloseableHttpClient client = HttpClientBuilder.create().build();
    final HttpPost request = new HttpPost(getBaseUrl() + "/opennms/rest/events");
    final Event ev = builder.getEvent();
    final String xml = JaxbUtils.marshal(ev);
    request.setHeader("Authorization", createBasicAuthHeader());
    request.setHeader("Content-Type", "application/xml");
    request.setHeader("Accept", "*/*");
    request.setEntity(new ByteArrayEntity(xml.getBytes("UTF-8")));
    final HttpResponse response = client.execute(request);
    final int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode != 200 && statusCode != 204) {
        throw new RuntimeException("bad response! " + response.getStatusLine().toString());
    }//from   www  .  ja  v  a 2s .c  o m
}

From source file:com.github.horrorho.inflatabledonkey.requests.ProtoBufsRequestFactory.java

public <T extends GeneratedMessage> HttpUriRequest newRequest(String url, String container, String bundle,
        String cloudKitUserId, String cloudKitToken, String uuid, List<T> protobufs) throws IOException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    protobufs.forEach(message -> {/*from   ww  w . j  a  va  2  s . co  m*/
        try {
            message.writeDelimitedTo(baos);

        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    });

    ByteArrayEntity byteArrayEntity = new ByteArrayEntity(baos.toByteArray());

    HttpPost post = new HttpPost(url);
    post.setHeader(Headers.XAPPLEREQUESTUUID.header(uuid));
    post.setHeader(Headers.XCLOUDKITUSERID.header(cloudKitUserId));
    post.setHeader(Headers.XCLOUDKITAUTHTOKEN.header(cloudKitToken));
    post.setHeader(Headers.XCLOUDKITCONTAINERID.header(container));
    post.setHeader(Headers.XCLOUDKITBUNDLEID.header(bundle));
    post.setHeader(HttpHeaders.ACCEPT, "application/x-protobuf");
    post.setHeader(HttpHeaders.CONTENT_TYPE,
            "application/x-protobuf; desc=\"https://p33-ckdatabase.icloud.com:443/static/protobuf/CloudDB/CloudDBClient.desc\"; messageType=RequestOperation; delimited=true");
    post.addHeader(headers.get(Headers.USERAGENT));
    post.addHeader(headers.get(Headers.XCLOUDKITPROTOCOLVERSION));
    post.addHeader(headers.get(Headers.XMMECLIENTINFO));
    post.setEntity(byteArrayEntity);

    return post;
}

From source file:com.github.grantjforrester.bdd.rest.httpclient.HttpClientRequest.java

HttpRequestBase getRequestImpl(URI baseUri) {
    HttpRequestBase request = null;/*from   w  w w.j  a v  a2  s  .c o m*/

    switch (method) {
    case HEAD:
        request = new HttpHead();
        break;
    case OPTIONS:
        request = new HttpOptions();
        break;
    case GET:
        request = new HttpGet();
        break;
    case POST:
        request = new HttpPost();
        break;
    case PUT:
        request = new HttpPut();
        break;
    case DELETE:
        request = new HttpDelete();
        break;
    case PATCH:
        request = new HttpPatch();
    }

    request.setURI(baseUri.resolve(uri));
    request.setHeaders(headers.toArray(new Header[headers.size()]));
    if (content != null) {
        ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(content));
    }

    return request;
}

From source file:com.foundationdb.server.service.security.RestSecurityIT.java

private int openRestURL(String request, String query, String userInfo, boolean post) throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpRequestBase httpRequest;/*from   w  w  w  . j  a va2s.  co  m*/
    if (post) {
        httpRequest = new HttpPost(getRestURL(request, "", userInfo));
        ((HttpPost) httpRequest).setEntity(new ByteArrayEntity(query.getBytes("UTF-8")));
    } else {
        httpRequest = new HttpGet(getRestURL(request, query, userInfo));
    }
    HttpResponse response = client.execute(httpRequest);
    int code = response.getStatusLine().getStatusCode();
    EntityUtils.consume(response.getEntity());
    client.close();
    return code;
}

From source file:com.github.horrorho.inflatabledonkey.requests.AuthorizeGetRequestFactory.java

public Optional<HttpUriRequest> newRequest(String dsPrsID, String contentBaseUrl, String container, String zone,
        CloudKit.FileTokens fileTokens) {

    if (fileTokens.getFileTokensCount() == 0) {
        return Optional.empty();
    }//from  w  ww. j a  va2 s.  c om

    CloudKit.FileToken base = fileTokens.getFileTokens(0);

    String mmcsAuthToken = Stream
            .of(Hex.encodeHexString(base.getFileChecksum().toByteArray()),
                    Hex.encodeHexString(base.getFileSignature().toByteArray()), base.getToken())
            .collect(Collectors.joining(" "));

    ByteArrayEntity byteArrayEntity = new ByteArrayEntity(fileTokens.toByteArray());

    String uri = contentBaseUrl + "/" + dsPrsID + "/authorizeGet";

    HttpUriRequest request = RequestBuilder.post(uri)
            .addHeader(Headers.ACCEPT.header("application/vnd.com.apple.me.ubchunk+protobuf"))
            .addHeader(Headers.CONTENTTYPE.header("application/vnd.com.apple.me.ubchunk+protobuf"))
            .addHeader(Headers.XAPPLEMMCSDATACLASS.header("com.apple.Dataclass.CloudKit"))
            .addHeader(Headers.XAPPLEMMCSAUTH.header(mmcsAuthToken))
            .addHeader(Headers.XAPPLEMMEDSID.header(dsPrsID))
            .addHeader(Headers.XCLOUDKITCONTAINER.header(container))
            .addHeader(Headers.XCLOUDKITZONES.header(zone)).addHeader(headers.get(Headers.USERAGENT))
            .addHeader(headers.get(Headers.XAPPLEMMCSPROTOVERSION))
            .addHeader(headers.get(Headers.XMMECLIENTINFO)).setEntity(byteArrayEntity).build();

    return Optional.of(request);
}

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

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *//*  w w w. ja  va 2  s .com*/
@SuppressWarnings("deprecation")
public 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:org.zalando.logbook.httpclient.Response.java

@Override
public org.zalando.logbook.HttpResponse withBody() throws IOException {
    @Nullable//from w  w w.  ja va 2 s  .  c  o  m
    final HttpEntity entity = response.getEntity();

    if (entity == null) {
        this.body = new byte[0];
        return this;
    }

    this.body = ByteStreams.toByteArray(entity.getContent());
    response.setEntity(new ByteArrayEntity(body));

    return this;
}