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, long j, ContentType contentType) 

Source Link

Usage

From source file: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 a  v  a  2 s .c  om
    }
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost("http://localhost/");

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

        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1,
                ContentType.APPLICATION_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());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:demo.example.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  a  v a  2 s . c om*/
    }
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost("http://httpbin.org/post");

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

        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1,
                ContentType.APPLICATION_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());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:httpclientdemo.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 a v  a 2  s . c  o  m*/
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost("http://httpbin.org/post");

        File file = new File("/Users/jack/Downloads/listdata (1).xlsx");

        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1,
                ContentType.APPLICATION_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());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:org.commonjava.maven.galley.transport.htcli.internal.HttpPublish.java

@Override
public HttpPublish call() {
    //            logger.info( "Trying: {}", url );
    final HttpPut put = new HttpPut(url);
    put.setEntity(new InputStreamEntity(stream, length, ContentType.create(contentType)));

    request = put;/*  ww  w.  j  a v a  2s  . c o  m*/

    try {
        success = executeHttp();
    } catch (final TransferException e) {
        this.error = e;
    } finally {
        cleanup();
    }

    return this;
}

From source file:eu.scape_project.fcrepo.integration.ReferencedContentIntellectualEntitiesIT.java

@Test
public void testIngestIntellectualEntityAndCheckRedirectForBinary() throws Exception {
    HttpPost post = new HttpPost(SCAPE_URL + "/entity");
    post.setEntity(//w w w  .ja v a2s .c  om
            new InputStreamEntity(this.getClass().getClassLoader().getResourceAsStream("ONB_mets_small.xml"),
                    -1, ContentType.TEXT_XML));
    HttpResponse resp = this.client.execute(post);
    String id = EntityUtils.toString(resp.getEntity());
    post.releaseConnection();

    HttpGet get = new HttpGet(SCAPE_URL + "/entity/" + id);
    resp = client.execute(get);
    assertEquals(200, resp.getStatusLine().getStatusCode());
    IntellectualEntity e = this.marshaller.deserialize(IntellectualEntity.class, resp.getEntity().getContent());
    get.releaseConnection();

    for (Representation r : e.getRepresentations()) {
        for (File f : r.getFiles()) {
            get = new HttpGet(SCAPE_URL + "/file/" + e.getIdentifier().getValue() + "/"
                    + r.getIdentifier().getValue() + "/" + f.getIdentifier().getValue());
            this.client.getParams().setBooleanParameter("http.protocol.handle-redirects", false);
            resp = this.client.execute(get);
            assertEquals(307, resp.getStatusLine().getStatusCode());
            assertEquals(f.getUri().toASCIIString(), resp.getFirstHeader("Location").getValue());
            get.releaseConnection();
        }
    }
}

From source file:eu.scape_project.fcrepo.integration.AbstractIT.java

protected void postEntity(IntellectualEntity ie) throws IOException {
    HttpPost post = new HttpPost(SCAPE_URL + "/entity");
    ByteArrayOutputStream sink = new ByteArrayOutputStream();
    try {/*w w w  .  ja va  2  s.  c  o  m*/
        this.marshaller.serialize(ie, sink);
    } catch (JAXBException e) {
        throw new IOException(e);
    }
    post.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink.toByteArray()), sink.size(),
            ContentType.TEXT_XML));
    HttpResponse resp = this.client.execute(post);
    assertEquals(201, resp.getStatusLine().getStatusCode());
    String id = EntityUtils.toString(resp.getEntity());
    assertTrue(id.length() > 0);
    post.releaseConnection();
}

From source file:com.clxcommunications.xms.JsonApiAsyncConsumer.java

@Override
protected T buildResult(HttpContext context) throws Exception {
    int code = response.getStatusLine().getStatusCode();
    InputStream inputStream = bios.toInputStream();

    switch (code) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
        return json.readValue(inputStream, jsonClass);
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_FORBIDDEN:
        ApiError error = json.readValue(inputStream, ApiError.class);
        throw new ErrorResponseException(error);
    case HttpStatus.SC_NOT_FOUND:
        HttpCoreContext coreContext = HttpCoreContext.adapt(context);
        RequestLine rl = coreContext.getRequest().getRequestLine();
        throw new NotFoundException(rl.getUri());
    case HttpStatus.SC_UNAUTHORIZED:
        throw new UnauthorizedException();
    default:/*from www . j a  v a2 s. co m*/
        ContentType type = ContentType.getLenient(response.getEntity());
        InputStreamEntity entity = new InputStreamEntity(inputStream, bios.size(), type);
        response.setEntity(entity);
        throw new UnexpectedResponseException(response);
    }
}

From source file:com.axelor.apps.account.ebics.client.HttpRequestSender.java

/**
 * Sends the request contained in the <code>ContentFactory</code>.
 * The <code>ContentFactory</code> will deliver the request as
 * an <code>InputStream</code>.
 *
 * @param request the ebics request/*from  www  .  j av  a  2  s.c  o m*/
 * @return the HTTP return code
* @throws AxelorException 
 */
public final int send(ContentFactory request) throws IOException, AxelorException {
    HttpClient httpClient;
    String proxyConfiguration;
    InputStream input;
    int retCode;

    httpClient = new HttpClient();
    EbicsBank bank = session.getUser().getEbicsPartner().getEbicsBank();
    DefaultHttpClient client = getSecuredHttpClient(EbicsCertificateService.getCertificate(bank, "ssl"));

    proxyConfiguration = AppSettings.get().get("http.proxy.host");

    if (proxyConfiguration != null && !proxyConfiguration.equals("")) {
        HostConfiguration hostConfig;
        String proxyHost;
        int proxyPort;

        hostConfig = httpClient.getHostConfiguration();
        proxyHost = AppSettings.get().get("http.proxy.host").trim();
        proxyPort = Integer.parseInt(AppSettings.get().get("http.proxy.port").trim());
        hostConfig.setProxy(proxyHost, proxyPort);
        if (!AppSettings.get().get("http.proxy.user").equals("")) {
            String user;
            String pwd;
            UsernamePasswordCredentials credentials;
            AuthScope authscope;

            user = AppSettings.get().get("http.proxy.user").trim();
            pwd = AppSettings.get().get("http.proxy.password").trim();
            credentials = new UsernamePasswordCredentials(user, pwd);
            authscope = new AuthScope(proxyHost, proxyPort);
            httpClient.getState().setProxyCredentials(authscope, credentials);
        }
    }

    input = request.getContent();
    retCode = -1;
    HttpPost post = new HttpPost(bank.getUrl());
    ContentType type = ContentType.TEXT_XML;
    HttpEntity entity = new InputStreamEntity(input, retCode, type);
    post.setEntity(entity);
    HttpResponse responseHttp = client.execute(post);
    retCode = responseHttp.getStatusLine().getStatusCode();
    response = new InputStreamContentFactory(responseHttp.getEntity().getContent());
    return retCode;
}

From source file:com.michaeljones.httpclient.apache.ApacheMethodClient.java

@Override
public int PutFile(String url, String filePath, List<Pair<String, String>> queryParams, StringBuilder redirect)
        throws FileNotFoundException {
    try {/*  w  w w.j  a va  2 s.  c o  m*/
        URIBuilder fileUri = new URIBuilder(url);

        if (queryParams != null) {
            // Query params are optional. In the case of a redirect the url will contain
            // all the params.
            for (Pair<String, String> queryParam : queryParams) {
                fileUri.addParameter(queryParam.getFirst(), queryParam.getSecond());
            }
        }

        HttpPut httpPut = new HttpPut(fileUri.build());
        InputStream fileInStream = new FileInputStream(filePath);
        InputStreamEntity chunkedStream = new InputStreamEntity(fileInStream, -1,
                ContentType.APPLICATION_OCTET_STREAM);
        chunkedStream.setChunked(true);

        httpPut.setEntity(chunkedStream);

        CloseableHttpResponse response = clientImpl.execute(httpPut);
        try {
            Header[] hdrs = response.getHeaders("Location");
            if (redirect != null && hdrs.length > 0) {
                String redirectLocation = hdrs[0].getValue();

                redirect.append(redirectLocation);
                LOGGER.debug("Redirect to: " + redirectLocation);
            }

            return response.getStatusLine().getStatusCode();
        } finally {
            // I believe this releases the connection to the client pool, but does not
            // close the connection.
            response.close();
        }
    } catch (IOException | URISyntaxException ex) {
        throw new RuntimeException("Apache method putQuery: " + ex.getMessage());
    }
}

From source file:com.servoy.extensions.plugins.http.BaseEntityEnclosingRequest.java

@Override
protected HttpEntity buildEntity() throws Exception {
    HttpEntity entity = null;//from ww w .  ja  v  a2s . c o  m
    if (files.size() == 0) {
        if (params != null) {
            entity = new UrlEncodedFormEntity(params, charset);
        } else if (!Utils.stringIsEmpty(content)) {
            entity = new StringEntity(content, mimeType, charset);
            content = null;
        }
    } else if (files.size() == 1 && (params == null || params.size() == 0)) {
        Object f = files.values().iterator().next();
        if (f instanceof File) {
            entity = new FileEntity((File) f, ContentType.create("binary/octet-stream")); //$NON-NLS-1$
        } else if (f instanceof JSFile) {
            entity = new InputStreamEntity(((JSFile) f).getAbstractFile().getInputStream(),
                    ((JSFile) f).js_size(), ContentType.create("binary/octet-stream")); //$NON-NLS-1$
        } else {
            Debug.error("could not add file to post request unknown type: " + f);
        }
    } else {
        entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // For File parameters
        for (Entry<Pair<String, String>, Object> e : files.entrySet()) {
            Object file = e.getValue();
            if (file instanceof File) {
                ((MultipartEntity) entity).addPart(e.getKey().getLeft(), new FileBody((File) file));
            } else if (file instanceof JSFile) {
                ((MultipartEntity) entity).addPart(e.getKey().getLeft(),
                        new ByteArrayBody(
                                Utils.getBytesFromInputStream(
                                        ((JSFile) file).getAbstractFile().getInputStream()),
                                "binary/octet-stream", ((JSFile) file).js_getName()));
            } else {
                Debug.error("could not add file to post request unknown type: " + file);
            }
        }

        // add the parameters
        if (params != null) {
            Iterator<NameValuePair> it = params.iterator();
            while (it.hasNext()) {
                NameValuePair nvp = it.next();
                // For usual String parameters
                ((MultipartEntity) entity).addPart(nvp.getName(),
                        new StringBody(nvp.getValue(), "text/plain", Charset.forName(charset)));
            }
        }
    }

    // entity may have been set already, see PutRequest.js_setFile
    return entity;
}