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:com.flowzr.rates.OpenExchangeRatesDownloaderTest.java

private String fileAsString(String fileName) {
    try {//w  w w  .j  a  va 2  s  . c om
        InputStream is = getInstrumentation().getContext().getResources().getAssets().open(fileName);
        InputStreamEntity entity = new InputStreamEntity(is, is.available());
        return EntityUtils.toString(entity);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.amazonaws.http.ApacheHttpClient.java

private HttpUriRequest createHttpRequest(HttpRequest request) {
    HttpUriRequest httpRequest;/* ww  w .  j a  va  2s  .  c o  m*/
    String method = request.getMethod();
    if (method.equals("POST")) {
        HttpPost postRequest = new HttpPost(request.getUri());
        if (request.getContent() != null) {
            postRequest.setEntity(new InputStreamEntity(request.getContent(), request.getContentLength()));
        }
        httpRequest = postRequest;
    } else if (method.equals("GET")) {
        httpRequest = new HttpGet(request.getUri());
    } else if (method.equals("PUT")) {
        HttpPut putRequest = new HttpPut(request.getUri());
        if (request.getContent() != null) {
            putRequest.setEntity(new InputStreamEntity(request.getContent(), request.getContentLength()));
        }
        httpRequest = putRequest;
    } else if (method.equals("DELETE")) {
        httpRequest = new HttpDelete(request.getUri());
    } else if (method.equals("HEAD")) {
        httpRequest = new HttpHead(request.getUri());
    } else {
        throw new UnsupportedOperationException("Unsupported method: " + method);
    }

    if (request.getHeaders() != null && !request.getHeaders().isEmpty()) {
        for (Map.Entry<String, String> header : request.getHeaders().entrySet()) {
            String key = header.getKey();
            /*
             * HttpClient4 fills in the Content-Length header and complains
             * if it's already present, so we skip it here. We also skip the
             * Host header to avoid sending it twice, which will interfere
             * with some signing schemes.
             */
            if (key.equals(HttpHeader.CONTENT_LENGTH) || key.equals(HttpHeader.HOST)) {
                continue;
            }
            httpRequest.addHeader(header.getKey(), header.getValue());
        }
    }

    // disable redirect
    if (params == null) {
        params = new BasicHttpParams();
        params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    }
    httpRequest.setParams(params);
    return httpRequest;
}

From source file:org.mahasen.client.Upload.java

/**
 * @param uploadFile// w  w  w  .  j a  v  a2 s  . c  o m
 * @param tags
 * @param folderStructure
 * @param addedProperties
 * @throws IOException
 */
public void upload(File uploadFile, String tags, String folderStructure, List<NameValuePair> addedProperties)
        throws IOException, MahasenClientException, URISyntaxException {
    httpclient = new DefaultHttpClient();

    if (addedProperties != null) {
        this.customProperties = addedProperties;
    }

    try {

        System.out.println(" Is Logged : " + clientLoginData.isLoggedIn());

        if (clientLoginData.isLoggedIn() == true) {

            httpclient = WebClientSSLWrapper.wrapClient(httpclient);

            File file = uploadFile;

            if (file.exists()) {

                if (!folderStructure.equals("")) {
                    customProperties.add(new BasicNameValuePair("folderStructure", folderStructure));
                }
                customProperties.add(new BasicNameValuePair("fileName", file.getName()));
                customProperties.add(new BasicNameValuePair("tags", tags));

                URI uri = URIUtils.createURI("https", clientLoginData.getHostNameAndPort(), -1,
                        "/mahasen/upload_ajaxprocessor.jsp", URLEncodedUtils.format(customProperties, "UTF-8"),
                        null);

                HttpPost httppost = new HttpPost(uri);

                InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
                reqEntity.setContentType("binary/octet-stream");
                reqEntity.setChunked(true);

                httppost.setEntity(reqEntity);

                httppost.setHeader("testHeader", "testHeadervalue");

                System.out.println("executing request " + httppost.getRequestLine());
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity resEntity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());

                EntityUtils.consume(resEntity);

                if (response.getStatusLine().getStatusCode() == 900) {
                    throw new MahasenClientException(String.valueOf(response.getStatusLine()));
                }

            }
        } else {
            System.out.println("User has to be logged in to perform this function");
        }
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

}

From source file:org.apache.solr.client.solrj.SolrSchemalessExampleTest.java

@Test
public void testArbitraryJsonIndexing() throws Exception {
    HttpSolrClient client = (HttpSolrClient) getSolrClient();
    client.deleteByQuery("*:*");
    client.commit();//from w w  w. ja  v  a  2 s. com
    assertNumFound("*:*", 0); // make sure it got in

    // two docs, one with uniqueKey, another without it
    String json = "{\"id\":\"abc1\", \"name\": \"name1\"} {\"name\" : \"name2\"}";
    HttpClient httpClient = client.getHttpClient();
    HttpPost post = new HttpPost(client.getBaseURL() + "/update/json/docs");
    post.setHeader("Content-Type", "application/json");
    post.setEntity(new InputStreamEntity(new ByteArrayInputStream(json.getBytes("UTF-8")), -1));
    HttpResponse response = httpClient.execute(post, HttpClientUtil.createNewHttpClientRequestContext());
    Utils.consumeFully(response.getEntity());
    assertEquals(200, response.getStatusLine().getStatusCode());
    client.commit();
    assertNumFound("*:*", 2);
}

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);/*  w  ww  . j  av a2 s  .co  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();
    }
}

From source file:org.gnode.wda.server.ProxyServlet.java

License:asdf

@Override
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Create new client to perform the proxied request
    HttpClient httpclient = new DefaultHttpClient();

    // Determine final URL
    StringBuffer uri = new StringBuffer();
    uri.append(targetServer);/*from www.  jav  a2 s  .  c  o m*/
    // This is a very bad hack. In order to remove my proxy servlet-path, I have used a substring method.
    // Turns "/proxy/asdf" into "/asdf"
    uri.append(req.getRequestURI().substring(6));

    //    Add any supplied query strings
    String queryString = req.getQueryString();
    if (queryString != null) {
        uri.append("?" + queryString);
    }

    // Get HTTP method
    final String method = req.getMethod();
    // Create new HTTP request container
    HttpRequestBase request = null;

    // Get content length
    int contentLength = req.getContentLength();
    //    Unknown content length ...
    // if (contentLength == -1)
    // throw new ServletException("Cannot handle unknown content length");
    // If we don't have an entity body, things are quite simple
    if (contentLength < 1) {
        request = new HttpRequestBase() {
            public String getMethod() {
                return method;
            }
        };
    } else {
        // Prepare request
        HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() {
            public String getMethod() {
                return method;
            }
        };

        // Transfer entity body from the received request to the new request
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength);
        tmpRequest.setEntity(entity);

        request = tmpRequest;
    }

    //    Set URI
    try {
        request.setURI(new URI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new ServletException("URISyntaxException: " + e.getMessage());
    }

    //       Copy headers from old request to new request
    // @todo not sure how this handles multiple headers with the same name
    Enumeration<String> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = headers.nextElement();
        String headerValue = req.getHeader(headerName);
        //       Skip Content-Length and Host
        String lowerHeader = headerName.toLowerCase();
        if (lowerHeader.equals("content-length") == false && lowerHeader.equals("host") == false) {
            //    System.out.println(headerName.toLowerCase() + ": " + headerValue);
            request.addHeader(headerName, headerValue);
        }
    }

    // Execute the request
    HttpResponse response = httpclient.execute(request);

    // Transfer status code to the response
    StatusLine status = response.getStatusLine();
    resp.setStatus(status.getStatusCode());
    // resp.setStatus(status.getStatusCode(), status.getReasonPhrase()); // This seems to be deprecated. Yes status message is "ambigous", but I don't approve

    // Transfer headers to the response
    Header[] responseHeaders = response.getAllHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header header = responseHeaders[i];
        resp.addHeader(header.getName(), header.getValue());
    }

    //    Transfer proxy response entity to the servlet response
    HttpEntity entity = response.getEntity();

    if (entity == null)
        return;

    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();
    int b = input.read();
    while (b != -1) {
        output.write(b);
        b = input.read();
    }

    //       Clean up
    input.close();
    output.close();
    httpclient.getConnectionManager().shutdown();
}

From source file:com.ibm.watson.developer_cloud.text_to_speech.v1.TextToSpeechTest.java

/**
 * Test synthesize.//from  www  .j  ava  2  s  .c  o  m
 */
@Test
public void testSynthesize() {
    File audio = new File("src/test/resources/sample1.wav");
    if (audio == null || !audio.exists() || !audio.isFile())
        throw new IllegalArgumentException("audio is not a valid audio file");

    InputStreamEntity reqEntity = null;
    try {
        reqEntity = new InputStreamEntity(new FileInputStream(audio), -1);
        List<Parameter> parameters = new ArrayList<Parameter>();
        parameters.add(new Parameter("text", text));
        parameters.add(new Parameter("voice", Voice.EN_MICHAEL.getName()));
        parameters.add(new Parameter("accept", MediaType.AUDIO_WAV));

        mockServer.when(request().withQueryStringParameters(parameters).withPath(SYNTHESIZE_PATH))
                .respond(response().withHeaders(new Header(HttpHeaders.Names.CONTENT_TYPE, MediaType.AUDIO_WAV))
                        .withBody(IOUtils.toString(reqEntity.getContent())));

        InputStream in = service.synthesize(text, Voice.EN_MICHAEL, MediaType.AUDIO_WAV);
        Assert.assertNotNull(in);

        writeInputStreamToOutputStream(in, new FileOutputStream("target/output.wav"));

    } catch (FileNotFoundException e) {
        Assert.fail(e.getMessage());
    } catch (IOException e) {
        Assert.fail(e.getMessage());
    }
}

From source file:org.carewebframework.vista.api.mbroker.BrokerResponse.java

public BrokerResponse(List<String> response) {
    super(createStatusLine(response.get(0)));
    ContentType contentType = null;/*from  www. ja va  2  s  .  c  o  m*/
    InputStream body = null;

    for (int i = 1; i < response.size(); i++) {
        String s = response.get(i).trim();

        if (s.isEmpty()) {
            body = new ListInputStream(response.subList(i + 1, response.size()));
            break;
        }

        String[] pcs = s.split("\\:", 2);
        Header header = new BasicHeader(pcs[0].trim(), pcs[1].trim());
        addHeader(header);

        if (contentType == null && header.getName().equalsIgnoreCase(HttpHeaders.CONTENT_TYPE)) {
            contentType = parseContentType(header.getValue());
        }
    }

    setEntity(new InputStreamEntity(body, contentType));
}

From source file:com.dp.bigdata.taurus.web.servlet.CreateTaskServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    // Determine final URL
    StringBuffer uri = new StringBuffer();

    if (req.getParameter("update") != null) {
        uri.append(targetUri).append("/").append(req.getParameter("update"));
    } else {//from w  ww  . j a v  a 2s.c  o  m
        uri.append(targetUri);
    }
    LOG.info("Access URI : " + uri.toString());
    // Get HTTP method
    final String method = req.getMethod();
    // Create new HTTP request container
    HttpRequestBase request = null;

    // Get content length
    int contentLength = req.getContentLength();
    // Unknown content length ...
    // if (contentLength == -1)
    // throw new ServletException("Cannot handle unknown content length");
    // If we don't have an entity body, things are quite simple
    if (contentLength < 1) {
        request = new HttpRequestBase() {
            public String getMethod() {
                return method;
            }
        };
    } else {
        // Prepare request
        HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() {
            public String getMethod() {
                return method;
            }
        };
        // Transfer entity body from the received request to the new request
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength);
        tmpRequest.setEntity(entity);
        request = tmpRequest;
    }

    // Set URI
    try {
        request.setURI(new URI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new ServletException("URISyntaxException: " + e.getMessage());
    }

    // Copy headers from old request to new request
    // @todo not sure how this handles multiple headers with the same name
    Enumeration<?> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        String headerValue = req.getHeader(headerName);
        //LOG.info("header: " + headerName + " value: " + headerValue);
        // Skip Content-Length and Host
        String lowerHeader = headerName.toLowerCase();
        if (lowerHeader.equals("content-type")) {
            request.addHeader(headerName, headerValue + ";charset=\"utf-8\"");
        } else if (!lowerHeader.equals("content-length") && !lowerHeader.equals("host")) {
            request.addHeader(headerName, headerValue);
        }
    }

    // Execute the request
    HttpResponse response = httpclient.execute(request);
    // Transfer status code to the response
    StatusLine status = response.getStatusLine();
    resp.setStatus(status.getStatusCode());

    // Transfer headers to the response
    Header[] responseHeaders = response.getAllHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header header = responseHeaders[i];
        if (!header.getName().equals("Transfer-Encoding"))
            resp.addHeader(header.getName(), header.getValue());
    }

    // Transfer proxy response entity to the servlet response
    HttpEntity entity = response.getEntity();
    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();

    byte buffer[] = new byte[50];
    while (input.read(buffer) != -1) {
        output.write(buffer);
    }
    //        int b = input.read();
    //        while (b != -1) {
    //            output.write(b);
    //            b = input.read();
    //        }
    // Clean up
    input.close();
    output.close();
    httpclient.getConnectionManager().shutdown();
}

From source file:org.overlord.apiman.service.client.http.HTTPServiceClient.java

/**
 * {@inheritDoc}/*from   w  w w.jav  a 2  s.co m*/
 */
@Override
public Response process(Request request) throws Exception {
    String method = "GET";

    if (request instanceof HTTPGatewayRequest) {
        method = ((HTTPGatewayRequest) request).getHTTPMethod();
    }

    String proxyRequestUri = rewriteUrlFromRequest(request);

    HttpRequest proxyRequest;

    //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
    if (request.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || request.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);

        java.io.InputStream is = new java.io.ByteArrayInputStream(request.getContent());

        InputStreamEntity entity = new InputStreamEntity(is, request.getContent().length);

        is.close();

        eProxyRequest.setEntity(entity);

        proxyRequest = eProxyRequest;
    } else {
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
    }

    copyRequestHeaders(request, proxyRequest);

    try {
        // Execute the request
        if (LOG.isLoggable(Level.FINER)) {
            LOG.finer("proxy " + method + " uri: " + request.getSourceURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }

        HttpResponse proxyResponse = _proxyClient
                .execute(URIUtils.extractHost(new java.net.URI(request.getServiceURI())), proxyRequest);

        Response resp = new HTTPGatewayResponse(proxyResponse);

        return (resp);

    } 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;
        }
        //noinspection ConstantConditions
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new RuntimeException(e);
    }
}