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

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

Introduction

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

Prototype

public void setContentType(Header header) 

Source Link

Usage

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);// w  w w  .  j  av  a2  s . 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);
        // ?
        // 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.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);/*  w  ww.ja  v a2s .c  o 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.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);//from  w w w.  j  av  a  2 s.  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:org.jclouds.http.httpnio.util.NioHttpUtils.java

public static void addEntityForContent(BasicHttpEntityEnclosingRequest apacheRequest, Object content,
        String contentType, long length) {
    if (content instanceof InputStream) {
        InputStream inputStream = (InputStream) content;
        if (length == -1)
            throw new IllegalArgumentException("you must specify size when content is an InputStream");
        InputStreamEntity entity = new InputStreamEntity(inputStream, length);
        entity.setContentType(contentType);
        apacheRequest.setEntity(entity);
    } else if (content instanceof String) {
        NStringEntity nStringEntity = null;
        try {//from   www . j a  v  a 2  s  . c  o m
            nStringEntity = new NStringEntity((String) content);
        } catch (UnsupportedEncodingException e) {
            throw new UnsupportedOperationException("Encoding not supported", e);
        }
        nStringEntity.setContentType(contentType);
        apacheRequest.setEntity(nStringEntity);
    } else if (content instanceof File) {
        apacheRequest.setEntity(new NFileEntity((File) content, contentType, true));
    } else if (content instanceof byte[]) {
        NByteArrayEntity entity = new NByteArrayEntity((byte[]) content);
        entity.setContentType(contentType);
        apacheRequest.setEntity(entity);
    } else {
        throw new UnsupportedOperationException("Content class not supported: " + content.getClass().getName());
    }
}

From source file:com.meplato.store2.MockResponse.java

/**
 * Parse a response from String contents.
 *
 * @param contents//from  w  w w  . j a  va  2 s  .c o m
 * @return String contents
 * @throws IOException
 * @throws HttpException
 * @throws ServiceException
 */
public static Response fromContents(String contents) throws IOException, HttpException, ServiceException {
    // If this code works, it was written by Georg Wall.
    SessionInputBufferImpl sib = new SessionInputBufferImpl(new HttpTransportMetricsImpl(), 65535);
    sib.bind(new ByteArrayInputStream(contents.getBytes(Consts.UTF_8)));
    DefaultHttpResponseParser parser = new DefaultHttpResponseParser(sib);
    HttpResponse httpResponse = parser.parse();
    int endOfHeader = contents.indexOf("\r\n\r\n");
    if (endOfHeader >= 0) {
        endOfHeader += 4; // for \r\n\r\n
        byte[] bytes = contents.getBytes(Consts.UTF_8);
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes, endOfHeader, bytes.length - endOfHeader);
        InputStreamEntity entity = new InputStreamEntity(bais);
        entity.setContentType(httpResponse.getFirstHeader("Content-Type"));
        entity.setContentEncoding(httpResponse.getFirstHeader("Content-Encoding"));
        httpResponse.setEntity(entity);
    }
    return new ApacheHttpResponse(httpResponse);
}

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 {//w  ww  .j  a va 2s .  c  o m
        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:org.acoustid.server.util.ParameterMap.java

public static ParameterMap parseRequest(HttpServletRequest request) throws IOException {
    String contentEncoding = request.getHeader("Content-Encoding");
    if (contentEncoding != null) {
        contentEncoding = contentEncoding.toLowerCase();
    }/*from   ww  w.  j av a 2  s .  c om*/
    String contentType = request.getContentType();
    Map<String, String[]> map;
    if ("gzip".equals(contentEncoding) && "application/x-www-form-urlencoded".equals(contentType)) {
        InputStream inputStream = new GZIPInputStream(request.getInputStream());
        InputStreamEntity entity = new InputStreamEntity(inputStream, -1);
        entity.setContentType(contentType);
        map = new HashMap<String, String[]>();
        for (NameValuePair param : URLEncodedUtils.parse(entity)) {
            String name = param.getName();
            String value = param.getValue();
            String[] values = map.get(name);
            if (values == null) {
                values = new String[] { value };
            } else {
                values = (String[]) ArrayUtils.add(values, value);
            }
            map.put(name, values);
        }
    } else {
        map = request.getParameterMap();
    }
    return new ParameterMap(map);
}

From source file:marytts.server.http.MaryHttpServerUtils.java

public static void toHttpResponse(InputStream stream, HttpResponse response, String contentType,
        long streamLength) throws IOException {
    InputStreamEntity body = new InputStreamEntity(stream, streamLength);
    body.setContentType(contentType);
    response.setEntity(body);/*from  w w w.ja v a  2 s . co  m*/
    response.setStatusCode(HttpStatus.SC_OK);
}

From source file:com.jonbanjo.cups.operations.HttpPoster.java

static OperationResult sendRequest(URL url, ByteBuffer ippBuf, InputStream documentStream, final AuthInfo auth)
        throws IOException {

    final OperationResult opResult = new OperationResult();

    if (ippBuf == null) {
        return null;
    }/*w  w w .  j  ava 2  s .  co  m*/

    if (url == null) {
        return null;
    }

    DefaultHttpClient client = new DefaultHttpClient();

    // will not work with older versions of CUPS!
    client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    client.getParams().setParameter("http.socket.timeout", SOCKET_TIMEOUT);
    client.getParams().setParameter("http.connection.timeout", CONNECTION_TIMEOUT);
    client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    client.getParams().setParameter("http.method.response.buffer.warnlimit", new Integer(8092));
    // probabaly not working with older CUPS versions
    client.getParams().setParameter("http.protocol.expect-continue", Boolean.valueOf(true));

    HttpPost httpPost;

    try {
        httpPost = new HttpPost(url.toURI());
    } catch (Exception e) {
        System.out.println(e.toString());
        return null;
    }

    httpPost.getParams().setParameter("http.socket.timeout", SOCKET_TIMEOUT);

    byte[] bytes = new byte[ippBuf.limit()];
    ippBuf.get(bytes);

    ByteArrayInputStream headerStream = new ByteArrayInputStream(bytes);
    // If we need to send a document, concatenate InputStreams
    InputStream inputStream = headerStream;
    if (documentStream != null) {
        inputStream = new SequenceInputStream(headerStream, documentStream);
    }

    // set length to -1 to advice the entity to read until EOF
    InputStreamEntity requestEntity = new InputStreamEntity(inputStream, -1);

    requestEntity.setContentType(IPP_MIME_TYPE);
    httpPost.setEntity(requestEntity);

    if (auth.reason == AuthInfo.AUTH_REQUESTED) {
        AuthHeader.makeAuthHeader(httpPost, auth);
        if (auth.reason == AuthInfo.AUTH_OK) {
            httpPost.addHeader(auth.getAuthHeader());
            //httpPost.addHeader("Authorization", "Basic am9uOmpvbmJveQ==");
        }
    }

    ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
        @Override
        public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            if (response.getStatusLine().getStatusCode() == 401) {
                auth.setHttpHeader(response.getFirstHeader("WWW-Authenticate"));
            } else {
                auth.reason = AuthInfo.AUTH_OK;
            }
            HttpEntity entity = response.getEntity();
            opResult.setHttResult(response.getStatusLine().toString());
            if (entity != null) {
                return EntityUtils.toByteArray(entity);
            } else {
                return null;
            }
        }
    };

    if (url.getProtocol().equals("https")) {

        Scheme scheme = JfSSLScheme.getScheme();
        if (scheme == null)
            return null;
        client.getConnectionManager().getSchemeRegistry().register(scheme);
    }

    byte[] result = client.execute(httpPost, handler);
    //String test = new String(result);
    IppResponse ippResponse = new IppResponse();

    opResult.setIppResult(ippResponse.getResponse(ByteBuffer.wrap(result)));
    opResult.setAuthInfo(auth);
    client.getConnectionManager().shutdown();
    return opResult;
}

From source file:org.openjena.riot.web.HttpOp.java

/** POST with response body.
 * The input stream is assumed to be UTF-8.
 *///from  w w  w  . j a  v a 2s.  c o m
public static void execHttpPost(String url, String contentType, InputStream input, int length,
        String acceptType, Map<String, HttpResponseHandler> handlers) {

    InputStreamEntity e = new InputStreamEntity(input, length);
    e.setContentType(contentType);
    e.setContentEncoding("UTF-8");
    execHttpPost(url, e, acceptType, handlers);
}