Example usage for org.apache.http.entity InputStreamEntity InputStreamEntity

List of usage examples for org.apache.http.entity InputStreamEntity InputStreamEntity

Introduction

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

Prototype

public InputStreamEntity(InputStream inputStream, ContentType contentType) 

Source Link

Usage

From source file:kornell.server.ProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    // Make the Request
    //note: we won't transfer the protocol version because I'm not sure it would truly be compatible
    String method = servletRequest.getMethod();
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);
    HttpRequest proxyRequest;//ww w.  j a  v a2 s.  c o m
    //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        // Add the input entity (streamed)
        //  note: we don't bother ensuring we close the servletInputStream since the container handles it
        eProxyRequest.setEntity(
                new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
        proxyRequest = eProxyRequest;
    } else
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);

    copyRequestHeaders(servletRequest, proxyRequest);

    setXForwardedForHeader(servletRequest, proxyRequest);

    HttpResponse proxyResponse = null;
    try {
        // Execute the request
        if (doLog) {
            log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }
        proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUriObj), proxyRequest);

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            //the response is already "committed" now without any body to send
            //TODO copy response headers?
            return;
        }

        // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the
        //  reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletResponse);

        // Send the content to the client
        copyResponseEntity(proxyResponse, servletResponse);

    } catch (Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        if (e instanceof ServletException)
            throw (ServletException) e;
        //noinspection ConstantConditions
        if (e instanceof IOException)
            throw (IOException) e;
        throw new RuntimeException(e);

    } finally {
        // make sure the entire entity was consumed, so the connection is released
        if (proxyResponse != null)
            consumeQuietly(proxyResponse.getEntity());
        if (proxyResponse != null)
            closeQuietly(servletResponse.getOutputStream());
    }
}

From source file:org.s1.testing.httpclient.TestHttpClient.java

/**
 *
 * @param u//from w ww.j  a  v a2 s .  com
 * @param data
 * @param headers
 * @return
 */
public HttpResponseBean post(String u, InputStream data, Map<String, String> headers) {
    if (headers == null)
        headers = new HashMap<String, String>();

    u = getURL(u, null);
    HttpPost post = new HttpPost(u);
    try {
        for (String h : headers.keySet()) {
            post.setHeader(h, headers.get(h));
        }
        HttpEntity request = new InputStreamEntity(data, -1);
        post.setEntity(request);
        client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Test Browser");
        client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        //client.getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY);

        HttpResponse resp = null;
        try {
            resp = client.execute(host, post, context);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        Map<String, String> rh = new HashMap<String, String>();
        for (Header h : resp.getAllHeaders()) {
            rh.put(h.getName(), h.getValue());
        }
        try {
            HttpResponseBean r = new HttpResponseBean(resp.getStatusLine().getStatusCode(), rh,
                    EntityUtils.toByteArray(resp.getEntity()));
            printIfError(u, r);
            return r;
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    } finally {
        post.releaseConnection();
    }
}

From source file:com.duokan.reader.domain.account.oauth.evernote.TEvernoteHttpClient.java

public void flush() throws TTransportException {
    long timer = System.currentTimeMillis();

    HttpEntity httpEntity = null;/*from  ww w  . j a v  a 2s .co  m*/

    // Extract request and reset buffer
    try {
        // Prepare http post request
        HttpPost request = new HttpPost(url_.toExternalForm());
        this.request = request;
        request.addHeader("Content-Type", "application/x-thrift");
        request.addHeader("Cache-Control", "no-transform");
        if (customHeaders_ != null) {
            for (Map.Entry<String, String> header : customHeaders_.entrySet()) {
                request.addHeader(header.getKey(), header.getValue());
            }
        }
        InputStreamEntity entity = new InputStreamEntity(requestBuffer_.getInputStream(),
                requestBuffer_.getSize());
        request.setEntity(entity);
        request.addHeader("Accept", "application/x-thrift");
        request.addHeader("User-Agent", userAgent == null ? "Java/THttpClient" : userAgent);
        request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

        DefaultHttpClient dHTTP = getHTTPClient();
        HttpResponse response = dHTTP.execute(request);
        httpEntity = response.getEntity();

        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode != 200) {
            if (httpEntity != null) {
                httpEntity.consumeContent();
            }
            throw new TTransportException("HTTP Response code: " + responseCode);
        }
        // Read the responses
        requestBuffer_.reset();
        inputStream_ = response.getEntity().getContent();
    } catch (IOException iox) {
        throw new TTransportException(iox);
    } catch (Exception ex) {
        throw new TTransportException(ex);
    } finally {
        try {
            requestBuffer_.reset();
        } catch (IOException e) {
        }
        this.request = null;
    }
}

From source file:com.intel.cosbench.client.swift.SwiftClient.java

public void storeStreamedObject(String container, String object, InputStream data, long length)
        throws IOException, SwiftException {
    SwiftResponse response = null;/*ww w  .  j a v  a2s  .com*/
    try {
        method = HttpClientUtil.makeHttpPut(getObjectPath(container, object));
        method.setHeader(X_AUTH_TOKEN, authToken);
        InputStreamEntity entity = new InputStreamEntity(data, length);
        if (length < 0)
            entity.setChunked(true);
        else
            entity.setChunked(false);
        entity.setContentType("application/octet-stream");
        ((HttpPut) method).setEntity(entity);
        response = new SwiftResponse(client.execute(method));
        if (response.getStatusCode() == SC_CREATED)
            return;
        if (response.getStatusCode() == SC_ACCEPTED)
            return;
        if (response.getStatusCode() == SC_NOT_FOUND)
            throw new SwiftFileNotFoundException("container not found: " + container,
                    response.getResponseHeaders(), response.getStatusLine());
        throw new SwiftException("unexpected return from server", response.getResponseHeaders(),
                response.getStatusLine());
    } finally {
        if (response != null)
            response.consumeResposeBody();
    }
}

From source file:com.clarionmedia.infinitum.http.rest.impl.CachingEnabledRestfulClient.java

@Override
public RestResponse executePost(String uri, InputStream messageBody, int messageBodyLength, String contentType,
        Map<String, String> headers) {
    HttpPost httpPost = new HttpPost(uri);
    for (Entry<String, String> header : headers.entrySet()) {
        httpPost.addHeader(header.getKey(), header.getValue());
    }//from   w  w  w  .  j  a va 2 s.  co  m
    httpPost.addHeader("content-type", contentType);
    httpPost.setEntity(new InputStreamEntity(messageBody, messageBodyLength));
    try {
        RequestWrapper request = new RequestWrapper(httpPost);
        return executeRequest(new HashableHttpRequest(request));
    } catch (ProtocolException e) {
        throw new InfinitumRuntimeException("Unable to execute request", e);
    }
}

From source file:com.evernote.client.conn.mobile.TEvernoteHttpClient.java

@Deprecated
public void flush() throws TTransportException {
    long timer = System.currentTimeMillis();

    HttpEntity httpEntity;//w w w  .  ja va  2s  . c om

    // Extract request and reset buffer
    try {
        // Prepare http post request
        HttpPost request = new HttpPost(url.toExternalForm());
        this.request = request;
        request.addHeader("Content-Type", "application/x-thrift");
        request.addHeader("Cache-Control", "no-transform");
        if (customHeaders != null) {
            for (Map.Entry<String, String> header : customHeaders.entrySet()) {
                request.addHeader(header.getKey(), header.getValue());
            }
        }
        InputStreamEntity entity = new InputStreamEntity(requestBuffer.getInputStream(),
                requestBuffer.getBytesWritten());
        request.setEntity(entity);
        request.addHeader("Accept", "application/x-thrift");
        request.addHeader("User-Agent", userAgent == null ? "Java/THttpClient" : userAgent);
        request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

        DefaultHttpClient dHTTP = getHTTPClient();
        //noinspection ConstantConditions
        HttpResponse response = dHTTP.execute(request);
        httpEntity = response.getEntity();

        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode != 200) {
            if (httpEntity != null) {
                httpEntity.consumeContent();
            }
            throw new TTransportException("HTTP Response code: " + responseCode);
        }
        // Read the responses
        requestBuffer.reset();
        inputStream = response.getEntity().getContent();
    } catch (Exception ex) {
        throw new TTransportException(ex);
    } finally {
        try {
            requestBuffer.reset();
        } catch (IOException ignored) {
        }
        this.request = null;
    }
}

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

public int post(byte[] data) throws IOException {
    log.debug("POST " + URL.toString());
    HttpPost httpPost = new HttpPost(URL.toString());
    if (isAuthByPrivateKey) {
        httpPost.setHeaders(headersArray);
    }/*from w w  w. ja v  a 2  s . c o m*/
    log.debug("Post send :" + data.length);

    InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(data), data.length);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(false);
    BufferedHttpEntity myEntity = null;
    try {
        myEntity = new BufferedHttpEntity(reqEntity);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        log.error(e);
    }

    httpPost.setEntity(myEntity);
    response = client.execute(targetHost, httpPost, localcontext);
    return response.getStatusLine().getStatusCode();
}

From source file:eu.europa.ec.markt.dss.validation102853.https.FileCacheDataLoader.java

@Override
public byte[] post(final String urlString, final byte[] content) throws DSSException {

    final String fileName = ResourceLoader.getNormalizedFileName(urlString);

    // The length for the InputStreamEntity is needed, because some receivers (on the other side) need this
    // information.
    // To determine the length, we cannot read the content-stream up to the end and re-use it afterwards.
    // This is because, it may not be possible to reset the stream (= go to position 0).
    // So, the solution is to cache temporarily the complete content data (as we do not expect much here) in a
    // byte-array.
    final byte[] digest = DSSUtils.digest(DigestAlgorithm.MD5, content);
    final String digestHexEncoded = DSSUtils.toHex(digest);
    final String cacheFileName = fileName + "." + digestHexEncoded;
    final File file = getCacheFile(cacheFileName);
    if (file.exists()) {

        LOG.debug("Cached file was used");
        final byte[] byteArray = DSSUtils.toByteArray(file);
        return byteArray;
    } else {/*from w  w  w.j  a  v  a  2  s.c om*/

        LOG.debug("There is no cached file!");
    }

    final byte[] returnedBytes;
    if (!isNetworkProtocol(urlString)) {

        final String resourcePath = resourceLoader.getAbsoluteResourceFolder(urlString.trim());
        final File fileResource = new File(resourcePath);
        returnedBytes = DSSUtils.toByteArray(fileResource);
        return returnedBytes;
    }

    HttpPost httpRequest = null;
    HttpResponse httpResponse = null;
    try {

        final URI uri = URI.create(urlString.trim());
        httpRequest = new HttpPost(uri);

        final ByteArrayInputStream bis = new ByteArrayInputStream(content);

        final HttpEntity requestEntity = new InputStreamEntity(bis, content.length);
        httpRequest.setEntity(requestEntity);
        if (contentType != null) {
            httpRequest.setHeader(CONTENT_TYPE, contentType);
        }

        httpResponse = super.getHttpResponse(httpRequest, urlString);

        returnedBytes = readHttpResponse(urlString, httpResponse);
        if (returnedBytes.length != 0) {

            final File cacheFile = getCacheFile(cacheFileName);
            DSSUtils.saveToFile(returnedBytes, cacheFile);
        }
    } finally {
        if (httpRequest != null) {
            httpRequest.releaseConnection();
        }
        if (httpResponse != null) {
            EntityUtils.consumeQuietly(httpResponse.getEntity());
        }
    }
    return returnedBytes;
}

From source file:cn.knet.showcase.demos.servletproxy.ProxyServlet.java

private HttpRequest newProxyRequestWithEntity(String method, String proxyRequestUri,
        HttpServletRequest servletRequest) throws IOException {
    HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
    // Add the input entity (streamed)
    //  note: we don't bother ensuring we close the servletInputStream since the container handles it
    eProxyRequest.setEntity(/*w w w .  j av  a2 s.  co  m*/
            new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
    return eProxyRequest;
}