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, ContentType contentType) 

Source Link

Usage

From source file:co.freeside.betamax.httpclient.BetamaxRequestDirector.java

private HttpResponse handleRequest(HttpRequest request) throws IOException {
    Request requestWrapper = new HttpRequestAdapter(request);
    Response responseWrapper = handlerChain.handle(requestWrapper);

    HttpResponse response = new BasicHttpResponse(HTTP_1_1, responseWrapper.getStatus(),
            EnglishReasonPhraseCatalog.INSTANCE.getReason(responseWrapper.getStatus(), ENGLISH));
    for (Map.Entry<String, String> header : responseWrapper.getHeaders().entrySet()) {
        for (String value : header.getValue().split(",")) {
            response.addHeader(header.getKey(), value.trim());
        }//from  www.j a v a2 s .co  m
    }
    if (responseWrapper.hasBody()) {
        response.setEntity(new ByteArrayEntity(ByteStreams.toByteArray(responseWrapper.getBodyAsBinary()),
                ContentType.create(responseWrapper.getContentType())));
    }
    return response;
}

From source file:com.seleritycorp.common.base.http.client.HttpResponseStreamTest.java

private HttpResponseStream createHttpResponseStream(int status, byte[] body, Charset charset) throws Exception {
    StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, status, "ReasonFoo");
    org.apache.http.HttpResponse backendResponse = new BasicHttpResponse(statusLine);
    if (body != null) {
        backendResponse.setEntity(new ByteArrayEntity(body, ContentType.create("foo", charset)));
    } else {/*from w  w  w . j  av  a2s.  c  o m*/
        backendResponse.setEntity(null);
    }
    return new HttpResponseStream(backendResponse);
}

From source file:org.obm.sync.push.client.XMLOPClient.java

private ByteArrayEntity getRequestEntity(Document doc)
        throws UnsupportedEncodingException, TransformerException {
    try {/*from w  ww  .  j a v a2 s . c  o  m*/
        String xmlData = DOMUtils.serialize(doc);
        return new ByteArrayEntity(xmlData.getBytes("UTF8"), ContentType.TEXT_XML);
    } catch (TransformerException e) {
        throw new TransformerException("Cannot serialize data to xml", e);
    }
}

From source file:com.nextdoor.bender.ipc.http.HttpTransport.java

protected HttpResponse sendBatchCompressed(HttpPost httpPost, byte[] raw) throws TransportException {
    /*// www  .j  a  v a  2 s  .c  o  m
     * Write gzip data to Entity and set content encoding to gzip
     */
    ByteArrayEntity entity = new ByteArrayEntity(raw, ContentType.DEFAULT_BINARY);
    entity.setContentEncoding("gzip");

    httpPost.addHeader(new BasicHeader("Accept-Encoding", "gzip"));
    httpPost.setEntity(entity);

    /*
     * Make call
     */
    HttpResponse resp = null;
    try {
        resp = this.client.execute(httpPost);
    } catch (IOException e) {
        throw new TransportException("failed to make call", e);
    }

    return resp;
}

From source file:io.github.kitarek.elasthttpd.commons.TemplatedHttpResponder.java

private void setupAsciiUsStringAsResponseEntity(HttpResponse response, String message) {
    response.setEntity(/*from  w ww.  j  a  v a 2 s  .  c om*/
            new ByteArrayEntity(getAsciiBytes(message), ContentType.create("text/plain", "US-ASCII")));
}

From source file:com.github.matthesrieke.jprox.JProxViaParameterServlet.java

private HttpUriRequest prepareRequest(HttpServletRequest req, String target) throws IOException {
    String method = req.getMethod();
    if (method.equals(HttpGet.METHOD_NAME)) {
        return new HttpGet(target);
    } else if (method.equals(HttpPost.METHOD_NAME)) {
        HttpPost post = new HttpPost(target);
        post.setEntity(new ByteArrayEntity(readInputStream(req.getInputStream(), req.getContentLength()),
                ContentType.parse(req.getContentType())));
        return post;
    }//from  www  . ja va  2s  .  c  o  m
    throw new UnsupportedOperationException("Only GET and POST are supported by this proxy.");
}

From source file:org.apache.metamodel.elasticsearch.rest.ElasticSearchRestClient.java

private static Request putMapping(final PutMappingRequest putMappingRequest) {
    final String endpoint = "/" + putMappingRequest.indices()[0] + "/_mapping/" + putMappingRequest.type();
    final ByteArrayEntity entity = new ByteArrayEntity(putMappingRequest.source().getBytes(),
            ContentType.APPLICATION_JSON);
    return new Request(HttpPut.METHOD_NAME, endpoint, Collections.emptyMap(), entity);
}

From source file:org.Cherry.Modules.Web.Engine.TemplateRequestHandler.java

@Override
public void handle(final RequestCommand command) throws HttpException, IOException {
    final WeakReference<CallDef> call = new WeakReference<CallDef>(scanRESTBeanURI(command.getUri()));

    final JSONAgentDefinition jsonAgent = getController(call.get().getControllerURI());

    assert null != jsonAgent : "Undefined controller for URI [" + command.getUri() + "]";

    final RESTMethodDefinition restMethodDef = jsonAgent.get(call.get().getMethodURI());

    assert null != restMethodDef : "Undefined controller method for URI [" + command.getUri() + "/"
            + call.get().getMethodURI() + "]";

    final Object result = restMethodDef.invoke((Object[]) null);

    AbstractHttpEntity entity = null;//from  w  w w.j  a v a 2 s .  c  om

    if (null != result) {
        final WeakReference<DictionaryModel> model = new WeakReference<DictionaryModel>(createModel());

        model.get().putAll((Map<?, ?>) result);

        final WeakReference<Writer> writer = new WeakReference<Writer>(new FastStringWriter());
        final WeakReference<RequestTemplateCommand> tmpltCmd = new WeakReference<RequestTemplateCommand>(
                new RequestTemplateCommand(command));
        String tmpltDoc;

        if (tmpltCmd.get().isRootCall())
            tmpltDoc = getWelcomeDoc();
        else
            tmpltDoc = tmpltCmd.get().getUri();

        try {
            getFreeMarkerService().process(tmpltDoc, model.get(), writer.get());
            entity = new ByteArrayEntity(((FastStringWriter) writer.get()).getBuffer().toString().getBytes(),
                    APPLICATION_HTML_CONTENT_TYPE);
        } catch (final Throwable t) {
            throw new IllegalStateException(t);
        }
    } else
        warn("JSON Controller returned null for expected result of type [{}]",
                restMethodDef.getBeanParameterType());

    if (null == entity)
        throw new IllegalStateException("Template file [" + command.getUri() + "] not found!");

    command.getResponse().setStatusCode(HttpStatus.SC_OK);
    command.getResponse().setEntity(entity);
}

From source file:org.ulyssis.ipp.publisher.HttpOutput.java

@Override
public void outputScore(Score score) {
    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(createSslCustomContext(),
            new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    try (CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build()) {
        HttpPost req = new HttpPost(options.getHttp().toURI());
        byte[] scoreBytes = Serialization.getJsonMapper().writeValueAsBytes(score);
        HttpEntity ent = new ByteArrayEntity(scoreBytes, ContentType.APPLICATION_JSON);
        req.setEntity(ent);//from   w  ww. j a  va  2s  .  c o m
        try (CloseableHttpResponse response = httpClient.execute(req)) {
            if (response.getStatusLine().getStatusCode() != 200) {
                LOG.error("Non-success result!");
                return;
            }
            HttpEntity entity = response.getEntity();
            if (entity.getContentLength() != 7L) {
                LOG.error("Non-success result!");
                return;
            }
            String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            if (!"SUCCESS".equals(result)) {
                LOG.error("Non-success result!");
                return;
            }
        }
    } catch (Exception e) {
        // TODO: DO SOMETHING WITH THE EXCEPTION!
        LOG.error("Exception", e);
    }
}

From source file:com.oracle.jes.samples.hellostorage.HttpElementPost.java

public void putData2() throws Exception {
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new RequestContent())
            .add(new RequestTargetHost()).add(new RequestConnControl()).add(new RequestUserAgent("Test/1.1"))
            .add(new RequestExpectContinue(true)).build();

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpCoreContext coreContext = HttpCoreContext.create();
    HttpHost host = new HttpHost("192.168.1.5", 8080);
    coreContext.setTargetHost(host);/*from  w w w  . j ava  2 s. c  o  m*/

    DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
    ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;

    try {

        HttpEntity[] requestBodies = {
                new StringEntity("This is the first test request",
                        ContentType.create("text/plain", Consts.UTF_8)),
                new ByteArrayEntity("This is the second test request".getBytes("UTF-8"),
                        ContentType.APPLICATION_OCTET_STREAM),
                new InputStreamEntity(
                        new ByteArrayInputStream(
                                "This is the third test request (will be chunked)".getBytes("UTF-8")),
                        ContentType.APPLICATION_OCTET_STREAM) };

        for (int i = 0; i < requestBodies.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket);
            }

            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
                    "/servlets-examples/servlet/RequestInfoExample");

            request.setEntity(requestBodies[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            httpexecutor.preProcess(request, httpproc, coreContext);
            HttpResponse response = httpexecutor.execute(request, conn, coreContext);
            httpexecutor.postProcess(response, httpproc, coreContext);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, coreContext)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}