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:at.orz.arangodb.sandbox.PostChunkTest.java

/**
 * @param args//  w  w w .  j a  v a2 s.  c o m
 */
public static void main(String[] args) throws Exception {

    HttpClient client = new DefaultHttpClient();

    HttpPost post = new HttpPost(
            "http://arango-test-server:9999/_api/import?collection=test1&createCollection=true&type=documents");
    //post.setEntity(new StringEntity("{\"xx\": \"123\"}{\"xx\": \"456\"}"));
    InputStreamEntity entity = new InputStreamEntity(
            new ByteArrayInputStream("{\"xx\": \"123\"}{\"xx\": \"456\"}".getBytes()), 26);
    entity.setChunked(true);
    post.setEntity(entity);

    HttpResponse res = client.execute(post);

    System.out.println(res.getStatusLine());

    post.releaseConnection();
}

From source file:com.hilatest.httpclient.apacheexample.ClientChunkEncodedPost.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println("File path not given");
        System.exit(1);/*from  w w w  .j ava 2  s  .co m*/
    }
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample");

    File file = new File(args[0]);

    InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(true);
    // It may be more appropriate to use FileEntity class in this particular 
    // instance but we are using a more generic InputStreamEntity to demonstrate
    // the capability to stream out data from any arbitrary source
    // 
    // FileEntity entity = new FileEntity(file, "binary/octet-stream"); 

    httppost.setEntity(reqEntity);

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

    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    if (resEntity != null) {
        System.out.println("Response content length: " + resEntity.getContentLength());
        System.out.println("Chunked?: " + resEntity.isChunked());
    }
    if (resEntity != null) {
        resEntity.consumeContent();
    }

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

From source file:com.mtea.macrotea_httpclient_study.ClientChunkEncodedPost.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println("File path not given");
        System.exit(1);/*from  w  ww .jav a 2 s.co  m*/
    }
    HttpClient httpclient = new DefaultHttpClient();
    try {
        HttpPost httppost = new HttpPost("http://localhost:8080/servlets-examples/servlet/RequestInfoExample");

        File file = new File(args[0]);

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

        httppost.setEntity(reqEntity);

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

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println("Response content length: " + resEntity.getContentLength());
            System.out.println("Chunked?: " + resEntity.isChunked());
        }
        //
        EntityUtils.consume(resEntity);
    } finally {
        //??httpclient???
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.dlmu.heipacker.crawler.client.ClientChunkEncodedPost.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println("File path not given");
        System.exit(1);//w w  w .jav  a 2s  .c o  m
    }
    HttpClient httpclient = new DefaultHttpClient();
    try {
        HttpPost httppost = new HttpPost(
                "http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample");

        File file = new File(args[0]);

        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
        reqEntity.setContentType("binary/octet-stream");
        reqEntity.setChunked(true);
        // It may be more appropriate to use FileEntity class in this particular
        // instance but we are using a more generic InputStreamEntity to demonstrate
        // the capability to stream out data from any arbitrary source
        //
        // FileEntity entity = new FileEntity(file, "binary/octet-stream");

        httppost.setEntity(reqEntity);

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

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println("Response content length: " + resEntity.getContentLength());
            System.out.println("Chunked?: " + resEntity.isChunked());
        }
        EntityUtils.consume(resEntity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.sourcecode.youku.ElementalHttpPost.java

public static void main(String[] args) throws Exception {

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpContext context = new BasicHttpContext(null);

    HttpHost host = new HttpHost("localhost", 8080);

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    try {//  w  w w . ja v a 2s.  c o  m

        HttpEntity[] requestBodies = { new StringEntity("This is the first test request", "UTF-8"),
                new ByteArrayEntity("This is the second test request".getBytes("UTF-8")),
                new InputStreamEntity(new ByteArrayInputStream(
                        "This is the third test request (will be chunked)".getBytes("UTF-8")), -1) };

        for (int i = 0; i < requestBodies.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
                    "/servlets-examples/servlet/RequestInfoExample");
            request.setEntity(requestBodies[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

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

From source file:org.bimserver.build.CreateGitHubRelease.java

public static void main(String[] args) {
    String username = args[0];//ww  w  .  ja  v a2  s .com
    String password = args[1];
    String repo = args[2];
    String project = args[3];
    String tagname = args[4];
    String name = args[5];
    String body = args[6];
    String draft = args[7];
    String prerelease = args[8];
    String filesString = args[9];
    String[] filenames = filesString.split(";");

    GitHubClient gitHubClient = new GitHubClient("api.github.com");
    gitHubClient.setCredentials(username, password);

    Map<String, String> map = new HashMap<String, String>();
    map.put("tag_name", tagname);
    // map.put("target_commitish", "test");
    map.put("name", name);
    map.put("body", body);
    //      map.put("draft", draft);
    //      map.put("prerelease", prerelease);
    try {
        String string = "/repos/" + repo + "/" + project + "/releases";
        System.out.println(string);
        JsonObject gitHubResponse = gitHubClient.post(string, map, JsonObject.class);
        System.out.println(gitHubResponse);
        String id = gitHubResponse.get("id").getAsString();

        HttpHost httpHost = new HttpHost("uploads.github.com", 443, "https");

        BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
        basicCredentialsProvider.setCredentials(new AuthScope(httpHost),
                new UsernamePasswordCredentials(username, password));

        HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier();

        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        CloseableHttpClient client = HttpClients.custom()
                .setDefaultCredentialsProvider(basicCredentialsProvider)
                .setHostnameVerifier((X509HostnameVerifier) hostnameVerifier).setSSLSocketFactory(sslsf)
                .build();

        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(httpHost, basicAuth);

        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(basicCredentialsProvider);
        context.setAuthCache(authCache);

        for (String filename : filenames) {
            File file = new File(filename);
            String url = "https://uploads.github.com/repos/" + repo + "/" + project + "/releases/" + id
                    + "/assets?name=" + file.getName();
            HttpPost post = new HttpPost(url);
            post.setHeader("Accept", "application/vnd.github.manifold-preview");
            post.setHeader("Content-Type", "application/zip");
            post.setEntity(new InputStreamEntity(new FileInputStream(file), file.length()));
            HttpResponse execute = client.execute(httpHost, post, context);
            execute.getEntity().getContent().close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
}

From source file:io.aos.protocol.http.httpcommon.ElementalHttpPost.java

public static void main(String... args) throws Exception {

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "Test/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpContext context = new BasicHttpContext(null);

    HttpHost host = new HttpHost("localhost", 8080);

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    try {/*w w w  .j  a v a2 s .  c o m*/

        HttpEntity[] requestBodies = { new StringEntity("This is the first test request", "UTF-8"),
                new ByteArrayEntity("This is the second test request".getBytes("UTF-8")),
                new InputStreamEntity(new ByteArrayInputStream(
                        "This is the third test request (will be chunked)".getBytes("UTF-8")), -1) };

        for (int i = 0; i < requestBodies.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
                    "/servlets-examples/servlet/RequestInfoExample");
            request.setEntity(requestBodies[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

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

From source file:Main.java

public static InputStreamEntity DocToInputStreamEntity(Document doc)
        throws TransformerFactoryConfigurationError, TransformerException {
    return new InputStreamEntity(new ByteArrayInputStream(DocToString(doc).getBytes()), -1);
}

From source file:com.wms.opensource.images3android.images3.ImageS3Service.java

public static int addImage(String baseUrl, String imagePlantId, String filePath) {
    File file = new File(filePath);
    try {/*from   w  ww. j a v  a  2s.c om*/
        HttpClient client = getClient();

        String url = baseUrl + imagePlantId + "/images";
        HttpPost httppost = new HttpPost(url);
        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
        reqEntity.setContentType("binary/octet-stream");
        reqEntity.setChunked(true);
        httppost.setEntity(reqEntity);
        HttpResponse response = client.execute(httppost);
        return response.getStatusLine().getStatusCode();
    } catch (Exception e) {
        return -1;
    }
}

From source file:it.govpay.web.console.utils.HttpClientUtils.java

public static HttpResponse sendRichiestaPagamento(String urlToInvoke, RichiestaPagamento richiestaPagamento,
        Logger log) throws Exception {
    HttpResponse responseGET = null;//from  w w  w. j a v a  2s .com
    try {
        log.debug("Invio del pagamento in corso...");

        URL urlObj = new URL(urlToInvoke);
        HttpHost target = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol());
        CloseableHttpClient client = HttpClientBuilder.create().disableRedirectHandling().build();
        HttpPost richiestaPost = new HttpPost();

        richiestaPost.setURI(urlObj.toURI());

        log.debug("Serializzazione pagamento in corso...");
        byte[] bufferPagamento = JaxbUtils.toBytes(richiestaPagamento);
        log.debug("Serializzazione pagamento completata.");

        HttpEntity bodyEntity = new InputStreamEntity(new ByteArrayInputStream(bufferPagamento),
                ContentType.APPLICATION_XML);
        richiestaPost.setEntity(bodyEntity);
        richiestaPost.setHeader("Content-Type", ContentType.APPLICATION_XML.getMimeType());

        log.debug("Invio tramite client Http in corso...");
        responseGET = client.execute(target, richiestaPost);

        if (responseGET == null)
            throw new NullPointerException("La Response HTTP e' null");

        log.debug("Invio tramite client Http completato.");
        return responseGET;
    } catch (Exception e) {
        log.error("Errore durante l'invio della richiesta di pagamento: " + e.getMessage(), e);
        throw e;
    }
}