Example usage for org.apache.http.entity BasicHttpEntity setContent

List of usage examples for org.apache.http.entity BasicHttpEntity setContent

Introduction

In this page you can find the example usage for org.apache.http.entity BasicHttpEntity setContent.

Prototype

public void setContent(InputStream inputStream) 

Source Link

Usage

From source file:be.cytomine.client.HttpClient.java

public int post(String data) throws IOException {
    log.debug("Post " + URL.getPath());
    HttpPost httpPost = new HttpPost(URL.toString());
    if (isAuthByPrivateKey) {
        httpPost.setHeaders(headersArray);
    }/*from  ww w. j a va  2  s .  c  o  m*/
    log.debug("Post send :" + data.replace("\n", ""));
    //write data
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(data.getBytes()));
    entity.setContentLength((long) data.getBytes().length);
    httpPost.setEntity(entity);
    response = client.execute(targetHost, httpPost, localcontext);
    return response.getStatusLine().getStatusCode();
}

From source file:be.cytomine.client.HttpClient.java

public int put(String data) throws IOException {
    log.debug("Put " + URL.getPath());
    HttpPut httpPut = new HttpPut(URL.toString());
    if (isAuthByPrivateKey) {
        httpPut.setHeaders(headersArray);
    }/*  w w w  .j  ava 2  s  . c om*/
    log.debug("Put send :" + data.replace("\n", ""));
    //write data
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(data.getBytes()));
    entity.setContentLength((long) data.getBytes().length);
    httpPut.setEntity(entity);
    response = client.execute(targetHost, httpPut, localcontext);
    return response.getStatusLine().getStatusCode();
}

From source file:com.gistlabs.mechanize.PageRequest.java

public HttpResponse consume(final HttpClient client, final HttpRequestBase request) throws Exception {
    if (!wasExecuted) {
        this.client = client;
        this.request = request;

        if (!request.getMethod().equalsIgnoreCase(httpMethod))
            throw new IllegalArgumentException(
                    String.format("Expected %s, but was %s", httpMethod, request.getMethod()));

        if (request.getURI().toString().equals(uri)) {
            HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK");
            BasicHttpEntity entity = new BasicHttpEntity();
            if (contentLocation != null)
                response.addHeader(new BasicHeader("Content-Location", contentLocation));
            entity.setContentEncoding(charset);
            entity.setContentType(this.contentType);
            entity.setContent(this.body);
            response.setEntity(new BufferedHttpEntity(entity));

            assertParameters(request);/*from   w  ww. jav  a 2 s . co m*/
            assertHeaders(request);

            this.wasExecuted = true;
            return response;
        } else {
            assertEquals("URI of the next PageRequest does not match", uri, request.getURI().toString());
            return null;
        }
    } else
        throw new UnsupportedOperationException("Request already executed");
}

From source file:jscover.server.PersistentStaticHttpServer.java

protected void sendOkContent(HttpServerConnection conn) throws IOException, HttpException {
    // send a 200 OK with the static content
    BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    BasicHttpEntity entity = new BasicHttpEntity();
    byte[] message = content.getBytes(Charset.forName("UTF-8"));
    entity.setContent(new ByteArrayInputStream(message));
    entity.setContentLength(message.length);
    response.setEntity(entity);/*from w  w w. ja  v a 2 s  . co  m*/

    // force Content-Length header so the client doesn't expect us to close the connection to end the response
    response.addHeader("Content-Length", String.valueOf(message.length));

    conn.sendResponseHeader(response);
    conn.sendResponseEntity(response);
    conn.flush();
    logger.log(FINE, "Sent 200 OK");
}

From source file:org.modelio.vbasic.net.ApacheUriConnection.java

/**
 * Same as {@link java.net.URLConnection#getOutputStream()}.
 * <p>/* w  w w .  j av  a  2  s. c o m*/
 * This implementation creates a {@link PipedOutputStream} to the Apache entity input stream.
 * It is strongly advised to <b>write to the returned stream in another thread</b>.
 * @see PipedOutputStream
 * @see PipedInputStream
 * @return an output stream that writes to this connection.
 * @throws java.io.IOException if an I/O error occurs while creating the output stream.
 */
@objid("79282b13-7e13-42d5-9917-892c78a155bd")
@Override
public OutputStream getOutputStream() throws IOException {
    if (!this.dooutput)
        throw new IllegalStateException("This is not an output connection");

    if (this.req != null && !(this.req instanceof HttpPut))
        throw new IllegalStateException("This is not an output connection");

    PipedOutputStream outPipe = new PipedOutputStream();
    PipedInputStream snk = new PipedInputStream(outPipe);
    outPipe.connect(snk);

    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(snk);

    HttpPut pr = (HttpPut) getRequest();
    pr.setEntity(entity);
    return outPipe;
}

From source file:com.lonepulse.zombielink.processor.RequestParamEndpointTest.java

/**
 * <p>Test for a {@link Request} with a <b>buffered</b> entity.</p>
 * //from w  w  w . j  a v  a2s  .c  om
 * @since 1.3.0
 */
@Test
public final void testBufferedHttpEntity() throws ParseException, IOException {

    String subpath = "/bufferedhttpentity";

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream inputStream = classLoader.getResourceAsStream("LICENSE.txt");
    InputStream parallelInputStream = classLoader.getResourceAsStream("LICENSE.txt");
    BasicHttpEntity bhe = new BasicHttpEntity();
    bhe.setContent(parallelInputStream);

    stubFor(put(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200)));

    requestEndpoint.bufferedHttpEntity(inputStream);

    verify(putRequestedFor(urlEqualTo(subpath))
            .withRequestBody(equalTo(EntityUtils.toString(new BufferedHttpEntity(bhe)))));
}

From source file:org.mycard.net.network.AndroidHttpClientConnection.java

/***
 * Return the next response entity.//from  ww  w  .  ja  v a  2  s.  c  om
 * @param headers contains values for parsing entity
 * @see HttpClientConnection#receiveResponseEntity(HttpResponse response)
 */
public HttpEntity receiveResponseEntity(final Headers headers) {
    assertOpen();
    BasicHttpEntity entity = new BasicHttpEntity();

    long len = determineLength(headers);
    if (len == ContentLengthStrategy.CHUNKED) {
        entity.setChunked(true);
        entity.setContentLength(-1);
        entity.setContent(new ChunkedInputStream(inbuffer));
    } else if (len == ContentLengthStrategy.IDENTITY) {
        entity.setChunked(false);
        entity.setContentLength(-1);
        entity.setContent(new IdentityInputStream(inbuffer));
    } else {
        entity.setChunked(false);
        entity.setContentLength(len);
        entity.setContent(new ContentLengthInputStream(inbuffer, len));
    }

    String contentTypeHeader = headers.getContentType();
    if (contentTypeHeader != null) {
        entity.setContentType(contentTypeHeader);
    }
    String contentEncodingHeader = headers.getContentEncoding();
    if (contentEncodingHeader != null) {
        entity.setContentEncoding(contentEncodingHeader);
    }

    return entity;
}

From source file:com.googlecode.noweco.calendar.test.CalendarClientTest.java

@Test
@Ignore/*w w  w.ja  v  a  2s .  com*/
public void test() throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    //        if (google || chandlerproject) {
    //            HttpParams params = httpclient.getParams();
    //            ConnRouteParams.setDefaultProxy(params, new HttpHost("ecprox.bull.fr"));
    //        }

    HttpEntityEnclosingRequestBase httpRequestBase = new HttpEntityEnclosingRequestBase() {

        @Override
        public String getMethod() {
            return "PROPFIND";
        }
    };

    BasicHttpEntity entity = new BasicHttpEntity();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream);
    //
    outputStreamWriter.write(
            "<?xml version=\"1.0\" encoding=\"utf-8\" ?><D:propfind xmlns:D=\"DAV:\">   <D:prop>  <D:displayname/>  <D:principal-collection-set/> <calendar-home-set xmlns=\"urn:ietf:params:xml:ns:caldav\"/>   </D:prop> </D:propfind>");
    outputStreamWriter.close();
    entity.setContent(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
    httpRequestBase.setEntity(entity);
    httpRequestBase.setURI(new URI("/dav/collection/gael.lalire@bull.com/"));
    if (google) {
        httpRequestBase.setURI(new URI("/calendar/dav/gael.lalire@gmail.com/user/"));
    }
    if (chandlerproject) {
        httpRequestBase.setURI(new URI("/dav/collection/8de93530-8796-11e0-82b8-d279848d8f3e"));
    }
    if (apple) {
        httpRequestBase.setURI(new URI("/"));
    }
    HttpHost target = new HttpHost("localhost", 8080);
    if (google) {
        target = new HttpHost("www.google.com", 443, "https");
    }
    if (chandlerproject) {
        target = new HttpHost("hub.chandlerproject.org", 443, "https");
    }
    if (apple) {
        target = new HttpHost("localhost", 8008, "http");
    }
    httpRequestBase.setHeader("Depth", "0");
    String userpass = null;
    if (apple) {
        userpass = "admin:admin";
    }
    httpRequestBase.setHeader("authorization", "Basic " + Base64.encodeBase64String(userpass.getBytes()));
    HttpResponse execute = httpclient.execute(target, httpRequestBase);
    System.out.println(Arrays.deepToString(execute.getAllHeaders()));
    System.out.println(execute.getStatusLine());
    System.out.println(EntityUtils.toString(execute.getEntity()));
}

From source file:org.geoserver.wms.map.MockHttpClientConnectionManager.java

@Override
public ConnectionRequest requestConnection(HttpRoute arg0, Object arg1) {
    return new ConnectionRequest() {

        @Override// w w w  .  j  a v  a2 s .c  om
        public boolean cancel() {
            return false;
        }

        @Override
        public HttpClientConnection get(long arg0, TimeUnit arg1)
                throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
            connections++;
            return new HttpClientConnection() {

                @Override
                public void shutdown() throws IOException {
                }

                @Override
                public void setSocketTimeout(int arg0) {
                }

                @Override
                public boolean isStale() {
                    return false;
                }

                @Override
                public boolean isOpen() {
                    return true;
                }

                @Override
                public int getSocketTimeout() {
                    return 0;
                }

                @Override
                public HttpConnectionMetrics getMetrics() {
                    return null;
                }

                @Override
                public void close() throws IOException {
                }

                @Override
                public void sendRequestHeader(HttpRequest arg0) throws HttpException, IOException {
                }

                @Override
                public void sendRequestEntity(HttpEntityEnclosingRequest arg0)
                        throws HttpException, IOException {
                }

                @Override
                public HttpResponse receiveResponseHeader() throws HttpException, IOException {
                    return new HttpResponse() {

                        List<Header> headers = new ArrayList<Header>();

                        @Override
                        public void addHeader(Header arg0) {
                        }

                        @Override
                        public void addHeader(String arg0, String arg1) {
                        }

                        @Override
                        public boolean containsHeader(String arg0) {
                            return false;
                        }

                        @Override
                        public Header[] getAllHeaders() {
                            return headers.toArray(new Header[] {});
                        }

                        public Header getHeader(String header) {
                            if ("transfer-encoding".equalsIgnoreCase(header)) {
                                return new BasicHeader(header, "identity");
                            }
                            if ("date".equalsIgnoreCase(header)) {

                                return new BasicHeader(header,
                                        dateFormat.format(new GregorianCalendar().getTime()));
                            }
                            if ("cache-control".equalsIgnoreCase(header)) {
                                return new BasicHeader(header, enableCache ? "public" : "no-cache");
                            }
                            if ("content-length".equalsIgnoreCase(header)) {
                                return new BasicHeader(header, response.length() + "");
                            }
                            if ("content-encoding".equalsIgnoreCase(header)) {
                                return new BasicHeader(header, "identity");
                            }
                            if ("age".equalsIgnoreCase(header)) {
                                return new BasicHeader(header, "0");
                            }
                            if ("expires".equalsIgnoreCase(header) && enableCache) {
                                GregorianCalendar expires = new GregorianCalendar();
                                expires.add(GregorianCalendar.MINUTE, 30);
                                return new BasicHeader(header, dateFormat.format(expires.getTime()));
                            }
                            return new BasicHeader(header, "");
                        }

                        @Override
                        public Header getFirstHeader(String header) {
                            Header value = getHeader(header);
                            headers.add(value);
                            return value;
                        }

                        @Override
                        public Header[] getHeaders(String header) {

                            return new Header[] { getFirstHeader(header) };
                        }

                        @Override
                        public Header getLastHeader(String header) {
                            return new BasicHeader(header, "");
                        }

                        @Override
                        public HttpParams getParams() {
                            // TODO Auto-generated method stub
                            return null;
                        }

                        @Override
                        public ProtocolVersion getProtocolVersion() {
                            return HttpVersion.HTTP_1_1;
                        }

                        @Override
                        public HeaderIterator headerIterator() {
                            return new BasicHeaderIterator(headers.toArray(new Header[] {}), "mock");
                        }

                        @Override
                        public HeaderIterator headerIterator(String header) {
                            return new BasicHeaderIterator(headers.toArray(new Header[] {}), "mock");
                        }

                        @Override
                        public void removeHeader(Header arg0) {
                        }

                        @Override
                        public void removeHeaders(String arg0) {
                        }

                        @Override
                        public void setHeader(Header arg0) {
                        }

                        @Override
                        public void setHeader(String arg0, String arg1) {
                        }

                        @Override
                        public void setHeaders(Header[] arg0) {
                        }

                        @Override
                        public void setParams(HttpParams arg0) {
                        }

                        @Override
                        public HttpEntity getEntity() {
                            BasicHttpEntity entity = new BasicHttpEntity();
                            entity.setContentLength(response.length());
                            entity.setContent(
                                    new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8)));
                            return entity;
                        }

                        @Override
                        public Locale getLocale() {
                            return Locale.ENGLISH;
                        }

                        @Override
                        public StatusLine getStatusLine() {
                            return new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK");
                        }

                        @Override
                        public void setEntity(HttpEntity arg0) {
                        }

                        @Override
                        public void setLocale(Locale arg0) {
                        }

                        @Override
                        public void setReasonPhrase(String arg0) throws IllegalStateException {
                        }

                        @Override
                        public void setStatusCode(int arg0) throws IllegalStateException {
                        }

                        @Override
                        public void setStatusLine(StatusLine arg0) {
                        }

                        @Override
                        public void setStatusLine(ProtocolVersion arg0, int arg1) {
                        }

                        @Override
                        public void setStatusLine(ProtocolVersion arg0, int arg1, String arg2) {
                        }
                    };
                }

                @Override
                public void receiveResponseEntity(HttpResponse arg0) throws HttpException, IOException {
                }

                @Override
                public boolean isResponseAvailable(int arg0) throws IOException {
                    return true;
                }

                @Override
                public void flush() throws IOException {
                }
            };
        }
    };
}