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:jsonbroker.library.client.http.HttpDispatcher.java

private HttpRequestBase buildPostRequest(HttpRequestAdapter requestAdapter, Authenticator authenticator) {

    String requestUri = requestAdapter.getRequestUri();
    Entity entity = requestAdapter.getRequestEntity();

    String host = _networkAddress.getHostAddress();
    int port = _networkAddress.getPort();

    String uri = String.format("http://%s:%d%s", host, port, requestUri);
    //       log.debug( uri, "uri" );

    HttpPost answer = new HttpPost(uri);

    // extra headers ... 
    {//  w  w  w . ja v a 2s  .  co m
        HashMap<String, String> requestHeaders = requestAdapter.getRequestHeaders();
        for (Map.Entry<String, String> item : requestHeaders.entrySet()) {
            answer.setHeader(item.getKey(), item.getValue());
        }
    }

    // auth headers ... 
    if (null != authenticator) {
        String authorization = authenticator.getRequestAuthorization(answer.getMethod(), requestUri, entity);
        log.debug(authorization, "authorization");
        if (null != authorization) {
            answer.addHeader("Authorization", authorization);
        }
    }

    InputStreamEntity inputStreamEntity = new InputStreamEntity(entity.getContent(), entity.getContentLength());
    answer.setEntity(inputStreamEntity);

    return answer;

}

From source file:com.intuit.karate.http.apache.ApacheHttpClient.java

@Override
protected HttpEntity getEntity(InputStream value, String mediaType) {
    return new InputStreamEntity(value, ContentType.create(mediaType));
}

From source file:io.personium.test.jersey.PersoniumRestAdapter.java

/**
 * PUT??./*from w w w  .j  a va2s.  c om*/
 * @param url ?URL
 * @param contentType 
 * @param is PUT?
 * @return HttpPut
 * @throws PersoniumException DAO
 */
protected final HttpPut makePutRequestByStream(final String url, final String contentType, final InputStream is)
        throws PersoniumException {
    HttpPut request = new HttpPut(url);
    InputStreamEntity body;
    body = new InputStreamEntity(is, -1);
    Boolean chunked = true;
    if (chunked != null) {
        body.setChunked(chunked);
    }
    request.setEntity(body);
    return request;
}

From source file:iristk.speech.nuancecloud.NuanceCloudRecognizerListener.java

private void initRequest() {
    try {/*from  ww w  .  j  a v a  2 s .c o m*/
        speechQueue.reset();

        InputStream inputStream;
        String codec;

        if (!(audioFormat.getSampleRate() == 8000 || audioFormat.getSampleRate() == 16000)) {
            System.err.println("Error: NuanceCloudRecognizer must get 8 or 16 Khz audio, not "
                    + audioFormat.getSampleRate());
        }

        if (useSpeex) {
            encodedQueue.reset();
            JSpeexEnc encoder = new JSpeexEnc((int) audioFormat.getSampleRate());
            encoder.startEncoding(speechQueue, encodedQueue);
            inputStream = encodedQueue.getInputStream();
            codec = "audio/x-speex;rate=" + (int) audioFormat.getSampleRate();
        } else {
            inputStream = speechQueue.getInputStream();
            codec = "audio/x-wav;codec=pcm;bit=16;rate=" + (int) audioFormat.getSampleRate();
        }

        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("appId", license.getAppId()));
        qparams.add(new BasicNameValuePair("appKey", license.getAppKey()));
        qparams.add(new BasicNameValuePair("id", DEVICE_ID));
        URI uri = URIUtils.createURI("https", HOSTNAME, 443, SERVLET, URLEncodedUtils.format(qparams, "UTF-8"),
                null);
        final HttpPost httppost = new HttpPost(uri);
        httppost.addHeader("Content-Type", codec);
        httppost.addHeader("Content-Language", language);
        httppost.addHeader("Accept-Language", language);
        httppost.addHeader("Accept", RESULTS_FORMAT);
        httppost.addHeader("Accept-Topic", LM);
        if (nuanceAudioSource != null) {
            httppost.addHeader("X-Dictation-AudioSource", nuanceAudioSource.name());
        }
        if (cookie != null)
            httppost.addHeader("Cookie", cookie);

        InputStreamEntity reqEntity = new InputStreamEntity(inputStream, -1);
        reqEntity.setContentType(codec);

        httppost.setEntity(reqEntity);

        postThread = new PostThread(httppost);

    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}

From source file:org.deegree.console.client.RequestBean.java

public void sendRequest() throws UnsupportedEncodingException {
    if (!request.startsWith("<?xml")) {
        request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + request;
    }//from   w w w  .j av  a  2  s  .co  m

    String targetUrl = getTargetUrl();
    LOG.debug("Try to send the following request to " + targetUrl + " : \n" + request);
    if (targetUrl != null && targetUrl.length() > 0 && request != null && request.length() > 0) {
        InputStream is = new ByteArrayInputStream(request.getBytes("UTF-8"));
        try {
            DURL u = new DURL(targetUrl);
            DefaultHttpClient client = enableProxyUsage(new DefaultHttpClient(), u);
            HttpPost post = new HttpPost(targetUrl);
            post.setHeader("Content-Type", "text/xml;charset=UTF-8");
            post.setEntity(new InputStreamEntity(is, -1));
            HttpResponse response = client.execute(post);
            Header[] headers = response.getHeaders("Content-Type");
            if (headers.length > 0) {
                mimeType = headers[0].getValue();
                LOG.debug("Response mime type: " + mimeType);
                if (!mimeType.toLowerCase().contains("xml")) {
                    this.response = null;
                    FacesMessage fm = MessageUtils.getFacesMessage(FacesMessage.SEVERITY_INFO,
                            "INFO_RESPONSE_NOT_XML");
                    FacesContext.getCurrentInstance().addMessage(null, fm);
                }
            }
            if (mimeType == null) {
                mimeType = "text/plain";
            }

            InputStream in = response.getEntity().getContent();
            File file = File.createTempFile("genericclient", ".xml");
            responseFile = file.getName().toString();
            FileOutputStream out = new FileOutputStream(file);
            try {
                IOUtils.copy(in, out);
            } finally {
                IOUtils.closeQuietly(out);
                IOUtils.closeQuietly(in);
            }
            BufferedReader reader = null;
            try {
                in = new BoundedInputStream(new FileInputStream(file), 1024 * 256);
                reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                StringBuilder sb = new StringBuilder();
                String s;
                while ((s = reader.readLine()) != null) {
                    sb.append(s);
                }
                this.response = sb.toString();
            } finally {
                IOUtils.closeQuietly(reader);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:org.gitana.platform.client.support.RemoteImpl.java

@Override
public void upload(String uri, byte[] bytes, String mimetype) throws Exception {
    InputStreamEntity entity = new InputStreamEntity(new ByteArrayInputStream(bytes), bytes.length);
    entity.setContentType(mimetype);//w  ww . ja  v  a  2s  . co  m

    String URL = buildURL(uri, false);

    HttpPost httpPost = new HttpPost(URL);
    httpPost.setEntity(entity);

    HttpResponse httpResponse = invoker.execute(httpPost);
    if (!HttpUtil.isOk(httpResponse)) {
        throw new RuntimeException("Upload failed: " + EntityUtils.toString(httpResponse.getEntity()));
    }

    // consume the response fully so that the client connection can be reused
    EntityUtils.consume(httpResponse.getEntity());
}

From source file:me.code4fun.roboq.Request.java

private HttpEntity createBody(Object o) {
    Object o1 = o instanceof Body ? ((Body) o).content : o;
    String c1 = o instanceof Body ? ((Body) o).contentType : null;

    if (o1 instanceof byte[]) {
        ByteArrayEntity entity = new ByteArrayEntity((byte[]) o1) {
            @Override//from  www. j  ava 2 s .  c  om
            public void writeTo(OutputStream outstream) throws IOException {
                super.writeTo(decorateBodyOutput(outstream));
            }
        };
        entity.setContentType(c1 != null ? c1 : DEFAULT_BINARY_CONTENT_TYPE);
        return entity;
    } else if (o1 instanceof InputStream) {
        Long len = o instanceof Body ? ((Body) o).length : null;
        if (len == null)
            throw new RoboqException("Missing length in body for upload InputStream");

        InputStreamEntity entity = new InputStreamEntity((InputStream) o1, len) {
            @Override
            public void writeTo(OutputStream outstream) throws IOException {
                super.writeTo(decorateBodyOutput(outstream));
            }
        };
        entity.setContentType(c1 != null ? c1 : DEFAULT_BINARY_CONTENT_TYPE);
        return entity;
    } else if (o1 instanceof File) {
        File f = (File) o1;
        return new FileEntity(f, c1 != null ? c1 : getFileContentType(f)) {
            @Override
            public void writeTo(OutputStream outstream) throws IOException {
                super.writeTo(decorateBodyOutput(outstream));
            }
        };
    } else {
        String s = o2s(o1, "");
        String encoding = selectValue(fieldsEncoding, prepared != null ? prepared.fieldsEncoding : null,
                "UTF-8");
        try {
            StringEntity entity;
            entity = new StringEntity(s, encoding) {
                @Override
                public void writeTo(OutputStream outstream) throws IOException {
                    super.writeTo(decorateBodyOutput(outstream));
                }
            };
            entity.setContentType(c1 != null ? c1 : DEFAULT_TEXT_CONTENT_TYPE);
            return entity;
        } catch (UnsupportedEncodingException e) {
            throw new RoboqException("Illegal encoding for request body", e);
        }
    }
}

From source file:org.apache.abdera2.common.protocol.Session.java

/**
 * Sends the specified method request to the specified URI. This can be used to send extension HTTP methods to a
 * server (e.g. PATCH, LOCK, etc)/*  w w  w.j a va2 s . co m*/
 * 
 * @param method The HTTP method
 * @param uri The request URI
 * @param in An InputStream providing the payload of the request
 * @param options The Request Options
 */
public <T extends ClientResponse> T execute(String method, String uri, InputStream in, RequestOptions options) {
    if (options == null)
        options = getDefaultRequestOptions().get();
    InputStreamEntity re = new InputStreamEntity(in, -1);
    re.setContentType(options.getContentType().toString());
    return (T) wrap(execute(method, uri, re, options));
}

From source file:com.google.gwt.jolokia.server.servlet.ProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    // initialize request attributes from caches if unset by a subclass by
    // this point
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }/*  w  w  w. j  av  a2 s  .  c  o  m*/
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // 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;
    // 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);

    //debugProxyRequest(proxyRequest);

    HttpResponse proxyResponse = null;
    try {
        // Execute the request
        if (doLog) {
            log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }
        proxyResponse = proxyClient.execute(getTargetHost(servletRequest), 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, servletRequest, 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());
        // Note: Don't need to close servlet outputStream:
        // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
    }
}