Example usage for org.apache.http.entity.mime.content InputStreamBody InputStreamBody

List of usage examples for org.apache.http.entity.mime.content InputStreamBody InputStreamBody

Introduction

In this page you can find the example usage for org.apache.http.entity.mime.content InputStreamBody InputStreamBody.

Prototype

public InputStreamBody(final InputStream in, final String mimeType, final String filename) 

Source Link

Usage

From source file:org.mariotaku.twidere.util.net.HttpClientImpl.java

@Override
public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException {
    try {//from  ww  w  .j  av a  2  s.co  m
        HttpRequestBase commonsRequest;

        final HostAddressResolver resolver = conf.getHostAddressResolver();
        final String urlString = req.getURL();
        final URI urlOrig;
        try {
            urlOrig = new URI(urlString);
        } catch (final URISyntaxException e) {
            throw new TwitterException(e);
        }
        final String host = urlOrig.getHost(), authority = urlOrig.getAuthority();
        final String resolvedHost = resolver != null ? resolver.resolve(host) : null;
        final String resolvedUrl = !isEmpty(resolvedHost)
                ? urlString.replace("://" + host, "://" + resolvedHost)
                : urlString;

        final RequestMethod method = req.getMethod();
        if (method == RequestMethod.GET) {
            commonsRequest = new HttpGet(resolvedUrl);
        } else if (method == RequestMethod.POST) {
            final HttpPost post = new HttpPost(resolvedUrl);
            // parameter has a file?
            boolean hasFile = false;
            final HttpParameter[] params = req.getParameters();
            if (params != null) {
                for (final HttpParameter param : params) {
                    if (param.isFile()) {
                        hasFile = true;
                        break;
                    }
                }
                if (!hasFile) {
                    if (params.length > 0) {
                        post.setEntity(new UrlEncodedFormEntity(params));
                    }
                } else {
                    final MultipartEntity me = new MultipartEntity();
                    for (final HttpParameter param : params) {
                        if (param.isFile()) {
                            final ContentBody body;
                            if (param.getFile() != null) {
                                body = new FileBody(param.getFile(), param.getContentType());
                            } else {
                                body = new InputStreamBody(param.getFileBody(), param.getFileName(),
                                        param.getContentType());
                            }
                            me.addPart(param.getName(), body);
                        } else {
                            final ContentBody body = new StringBody(param.getValue(),
                                    "text/plain; charset=UTF-8", Charset.forName("UTF-8"));
                            me.addPart(param.getName(), body);
                        }
                    }
                    post.setEntity(me);
                }
            }
            post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
            commonsRequest = post;
        } else if (method == RequestMethod.DELETE) {
            commonsRequest = new HttpDelete(resolvedUrl);
        } else if (method == RequestMethod.HEAD) {
            commonsRequest = new HttpHead(resolvedUrl);
        } else if (method == RequestMethod.PUT) {
            commonsRequest = new HttpPut(resolvedUrl);
        } else
            throw new TwitterException("Unsupported request method " + method);
        final Map<String, String> headers = req.getRequestHeaders();
        for (final String headerName : headers.keySet()) {
            commonsRequest.addHeader(headerName, headers.get(headerName));
        }
        final Authorization authorization = req.getAuthorization();
        final String authorizationHeader = authorization != null ? authorization.getAuthorizationHeader(req)
                : null;
        if (authorizationHeader != null) {
            commonsRequest.addHeader("Authorization", authorizationHeader);
        }
        if (resolvedHost != null && !resolvedHost.isEmpty() && !resolvedHost.equals(host)) {
            commonsRequest.addHeader("Host", authority);
        }

        final ApacheHttpClientHttpResponseImpl res;
        try {
            res = new ApacheHttpClientHttpResponseImpl(client.execute(commonsRequest), conf);
        } catch (final IllegalStateException e) {
            throw new TwitterException("Please check your API settings.", e);
        } catch (final NullPointerException e) {
            // Bug http://code.google.com/p/android/issues/detail?id=5255
            throw new TwitterException("Please check your APN settings, make sure not to use WAP APNs.", e);
        } catch (final OutOfMemoryError e) {
            // I don't know why OOM thown, but it should be catched.
            System.gc();
            throw new TwitterException("Unknown error", e);
        }
        final int statusCode = res.getStatusCode();
        if (statusCode < OK || statusCode > ACCEPTED)
            throw new TwitterException(res.asString(), req, res);
        return res;
    } catch (final IOException e) {
        throw new TwitterException(e);
    }
}

From source file:ch.cyberduck.core.dropbox.DropboxPath.java

@Override
protected void upload(final BandwidthThrottle throttle, final StreamListener listener, final boolean check) {
    if (attributes().isFile()) {
        try {//from   www  . j av  a 2 s  .com
            if (check) {
                this.getSession().check();
            }

            final Status status = this.status();
            status.setResume(false);

            final Local local = this.getLocal();
            final InputStream in = local.getInputStream();
            try {
                this.getSession().getClient().put(this.getParent().getAbsolute(),
                        new InputStreamBody(in, local.getMimeType(), this.getName()) {
                            @Override
                            public void writeTo(OutputStream out) throws IOException {
                                upload(out, in, throttle, listener);
                            }

                            @Override
                            public long getContentLength() {
                                return local.attributes().getSize();
                            }
                        });
            } catch (IOException e) {
                this.status().setComplete(false);
                throw e;
            } finally {
                IOUtils.closeQuietly(in);
            }
        } catch (IOException e) {
            this.error("Upload failed", e);
        }
    }
}

From source file:com.linkedin.pinot.common.utils.FileUploadDownloadClient.java

private static ContentBody getContentBody(String fileName, InputStream inputStream) {
    return new InputStreamBody(inputStream, ContentType.DEFAULT_BINARY, fileName);
}

From source file:com.reachcall.pretty.http.ProxyServlet.java

@SuppressWarnings("unchecked")
private void doMultipart(HttpPost method, HttpServletRequest req)
        throws ServletException, FileUploadException, UnsupportedEncodingException, IOException {
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(TEMP_DIR);

    ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);

    List<FileItem> fileItems = (List<FileItem>) upload.parseRequest(req);

    MultipartEntity entity = new MultipartEntity();

    for (FileItem fItem : fileItems) {
        if (fItem.isFormField()) {
            LOG.log(Level.INFO, "Form field {0}", fItem.getName());

            StringBody part = new StringBody(fItem.getFieldName());
            entity.addPart(fItem.getFieldName(), part);
        } else {/*  w  ww.  j  a  v a  2s .c om*/
            LOG.log(Level.INFO, "File item {0}", fItem.getName());

            InputStreamBody file = new InputStreamBody(fItem.getInputStream(), fItem.getName(),
                    fItem.getContentType());
            entity.addPart(fItem.getFieldName(), file);
        }
    }

    method.setEntity(entity);
}

From source file:org.apache.manifoldcf.agents.output.solr.ModifiedHttpSolrServer.java

@Override
public NamedList<Object> request(final SolrRequest request, final ResponseParser processor)
        throws SolrServerException, IOException {
    HttpRequestBase method = null;// w  w w .  ja v  a2s  .c  o  m
    InputStream is = null;
    SolrParams params = request.getParams();
    Collection<ContentStream> streams = requestWriter.getContentStreams(request);
    String path = requestWriter.getPath(request);
    if (path == null || !path.startsWith("/")) {
        path = DEFAULT_PATH;
    }

    ResponseParser parser = request.getResponseParser();
    if (parser == null) {
        parser = this.parser;
    }

    // The parser 'wt=' and 'version=' params are used instead of the original
    // params
    ModifiableSolrParams wparams = new ModifiableSolrParams(params);
    if (parser != null) {
        wparams.set(CommonParams.WT, parser.getWriterType());
        wparams.set(CommonParams.VERSION, parser.getVersion());
    }
    if (invariantParams != null) {
        wparams.add(invariantParams);
    }
    params = wparams;

    int tries = maxRetries + 1;
    try {
        while (tries-- > 0) {
            // Note: since we aren't do intermittent time keeping
            // ourselves, the potential non-timeout latency could be as
            // much as tries-times (plus scheduling effects) the given
            // timeAllowed.
            try {
                if (SolrRequest.METHOD.GET == request.getMethod()) {
                    if (streams != null) {
                        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
                    }
                    method = new HttpGet(baseUrl + path + toQueryString(params, false));
                } else if (SolrRequest.METHOD.POST == request.getMethod()) {

                    String url = baseUrl + path;
                    boolean hasNullStreamName = false;
                    if (streams != null) {
                        for (ContentStream cs : streams) {
                            if (cs.getName() == null) {
                                hasNullStreamName = true;
                                break;
                            }
                        }
                    }
                    boolean isMultipart = (this.useMultiPartPost || (streams != null && streams.size() > 1))
                            && !hasNullStreamName;

                    LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>();
                    if (streams == null || isMultipart) {
                        HttpPost post = new HttpPost(url);
                        post.setHeader("Content-Charset", "UTF-8");
                        if (!isMultipart) {
                            post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                        }

                        List<FormBodyPart> parts = new LinkedList<FormBodyPart>();
                        Iterator<String> iter = params.getParameterNamesIterator();
                        while (iter.hasNext()) {
                            String p = iter.next();
                            String[] vals = params.getParams(p);
                            if (vals != null) {
                                for (String v : vals) {
                                    if (isMultipart) {
                                        parts.add(
                                                new FormBodyPart(p, new StringBody(v, StandardCharsets.UTF_8)));
                                    } else {
                                        postParams.add(new BasicNameValuePair(p, v));
                                    }
                                }
                            }
                        }

                        if (isMultipart && streams != null) {
                            for (ContentStream content : streams) {
                                String contentType = content.getContentType();
                                if (contentType == null) {
                                    contentType = "application/octet-stream"; // default
                                }
                                String contentName = content.getName();
                                parts.add(new FormBodyPart(contentName, new InputStreamBody(content.getStream(),
                                        contentType, content.getName())));
                            }
                        }

                        if (parts.size() > 0) {
                            ModifiedMultipartEntity entity = new ModifiedMultipartEntity(
                                    HttpMultipartMode.STRICT, null, StandardCharsets.UTF_8);
                            for (FormBodyPart p : parts) {
                                entity.addPart(p);
                            }
                            post.setEntity(entity);
                        } else {
                            //not using multipart
                            post.setEntity(new UrlEncodedFormEntity(postParams, StandardCharsets.UTF_8));
                        }

                        method = post;
                    }
                    // It is has one stream, it is the post body, put the params in the URL
                    else {
                        String pstr = toQueryString(params, false);
                        HttpPost post = new HttpPost(url + pstr);

                        // Single stream as body
                        // Using a loop just to get the first one
                        final ContentStream[] contentStream = new ContentStream[1];
                        for (ContentStream content : streams) {
                            contentStream[0] = content;
                            break;
                        }
                        if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
                            post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
                                @Override
                                public Header getContentType() {
                                    return new BasicHeader("Content-Type", contentStream[0].getContentType());
                                }

                                @Override
                                public boolean isRepeatable() {
                                    return false;
                                }

                            });
                        } else {
                            post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
                                @Override
                                public Header getContentType() {
                                    return new BasicHeader("Content-Type", contentStream[0].getContentType());
                                }

                                @Override
                                public boolean isRepeatable() {
                                    return false;
                                }
                            });
                        }
                        method = post;
                    }
                } else {
                    throw new SolrServerException("Unsupported method: " + request.getMethod());
                }
            } catch (NoHttpResponseException r) {
                method = null;
                if (is != null) {
                    is.close();
                }
                // If out of tries then just rethrow (as normal error).
                if (tries < 1) {
                    throw r;
                }
            }
        }
    } catch (IOException ex) {
        throw new SolrServerException("error reading streams", ex);
    }

    // XXX client already has this set, is this needed?
    //method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,
    //    followRedirects);
    method.addHeader("User-Agent", AGENT);

    InputStream respBody = null;
    boolean shouldClose = true;

    try {
        // Execute the method.
        final HttpResponse response = httpClient.execute(method);
        int httpStatus = response.getStatusLine().getStatusCode();

        // Read the contents
        respBody = response.getEntity().getContent();

        // handle some http level checks before trying to parse the response
        switch (httpStatus) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_BAD_REQUEST:
        case HttpStatus.SC_CONFLICT: // 409
            break;
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_MOVED_TEMPORARILY:
            if (!followRedirects) {
                throw new SolrServerException(
                        "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ").");
            }
            break;
        default:
            throw new SolrException(SolrException.ErrorCode.getErrorCode(httpStatus),
                    "Server at " + getBaseURL() + " returned non ok status:" + httpStatus + ", message:"
                            + response.getStatusLine().getReasonPhrase());

        }
        if (processor == null) {
            // no processor specified, return raw stream
            NamedList<Object> rsp = new NamedList<Object>();
            rsp.add("stream", respBody);
            // Only case where stream should not be closed
            shouldClose = false;
            return rsp;
        }
        Charset charsetObject = ContentType.getOrDefault(response.getEntity()).getCharset();
        String charset;
        if (charsetObject != null)
            charset = charsetObject.name();
        else
            charset = "utf-8";
        NamedList<Object> rsp = processor.processResponse(respBody, charset);
        if (httpStatus != HttpStatus.SC_OK) {
            String reason = null;
            try {
                NamedList err = (NamedList) rsp.get("error");
                if (err != null) {
                    reason = (String) err.get("msg");
                    // TODO? get the trace?
                }
            } catch (Exception ex) {
            }
            if (reason == null) {
                StringBuilder msg = new StringBuilder();
                msg.append(response.getStatusLine().getReasonPhrase());
                msg.append("\n\n");
                msg.append("request: " + method.getURI());
                reason = URLDecoder.decode(msg.toString());
            }
            throw new SolrException(SolrException.ErrorCode.getErrorCode(httpStatus), reason);
        }
        return rsp;
    } catch (ConnectException e) {
        throw new SolrServerException("Server refused connection at: " + getBaseURL(), e);
    } catch (SocketTimeoutException e) {
        throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(),
                e);
    } catch (IOException e) {
        throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e);
    } finally {
        if (respBody != null && shouldClose) {
            try {
                respBody.close();
            } catch (Throwable t) {
            } // ignore
        }
    }
}

From source file:de.vanita5.twittnuker.util.net.TwidereHttpClientImpl.java

private static HttpEntity getAsEntity(final HttpParameter[] params) throws UnsupportedEncodingException {
    if (params == null)
        return null;
    if (!HttpParameter.containsFile(params))
        return new HttpParameterFormEntity(params);
    final MultipartEntityBuilder me = MultipartEntityBuilder.create();
    for (final HttpParameter param : params) {
        if (param.isFile()) {
            final ContentType contentType = ContentType.create(param.getContentType());
            final ContentBody body;
            if (param.getFile() != null) {
                body = new FileBody(param.getFile(), ContentType.create(param.getContentType()));
            } else {
                body = new InputStreamBody(param.getFileBody(), contentType, param.getFileName());
            }//from w  ww .ja  v a  2 s. co  m
            me.addPart(param.getName(), body);
        } else {
            final ContentType contentType = ContentType.TEXT_PLAIN.withCharset(Consts.UTF_8);
            final ContentBody body = new StringBody(param.getValue(), contentType);
            me.addPart(param.getName(), body);
        }
    }
    return me.build();
}

From source file:com.smartling.api.sdk.FileApiClientAdapterImpl.java

@Override
public ApiResponse<UploadFileData> uploadFile(final InputStream inputStream, final String fileName,
        final String charsetName, final FileUploadParameterBuilder fileUploadParameterBuilder)
        throws ApiException {
    InputStreamBody inputStreamBody = new InputStreamBody(inputStream,
            createContentType(fileUploadParameterBuilder.getFileType(), Charset.forName(charsetName)),
            fileName);/*from  w  ww.j  a v a  2 s. com*/
    return uploadFile(fileUploadParameterBuilder, inputStreamBody);
}

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

@Override
protected HttpEntity getEntity(List<MultiPartItem> items, String mediaType) {
    boolean hasNullName = false;
    for (MultiPartItem item : items) {
        if (item.getName() == null) {
            hasNullName = true;// www.j  a v a 2 s . co  m
            break;
        }
    }
    if (hasNullName) { // multipart/related
        String boundary = createBoundary();
        String text = getAsStringEntity(items, boundary);
        ContentType ct = ContentType.create(mediaType)
                .withParameters(new BasicNameValuePair("boundary", boundary));
        return new StringEntity(text, ct);
    } else {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                .setContentType(ContentType.create(mediaType));
        for (MultiPartItem item : items) {
            if (item.getValue() == null || item.getValue().isNull()) {
                logger.warn("ignoring null multipart value for key: {}", item.getName());
                continue;
            }
            String name = item.getName();
            ScriptValue sv = item.getValue();
            if (name == null) {
                // builder.addPart(bodyPart);
            } else {
                FormBodyPartBuilder formBuilder = FormBodyPartBuilder.create().setName(name);
                ContentBody contentBody;
                switch (sv.getType()) {
                case INPUT_STREAM:
                    InputStream is = (InputStream) sv.getValue();
                    contentBody = new InputStreamBody(is, ContentType.APPLICATION_OCTET_STREAM, name);
                    break;
                case XML:
                    contentBody = new StringBody(sv.getAsString(), ContentType.APPLICATION_XML);
                    break;
                case JSON:
                    contentBody = new StringBody(sv.getAsString(), ContentType.APPLICATION_JSON);
                    break;
                default:
                    contentBody = new StringBody(sv.getAsString(), ContentType.TEXT_PLAIN);
                }
                formBuilder = formBuilder.setBody(contentBody);
                builder = builder.addPart(formBuilder.build());
            }
        }
        return builder.build();
    }
}

From source file:com.puppetlabs.geppetto.forge.client.ForgeHttpClient.java

@Override
public <V> V postUpload(String uri, Map<String, String> stringParts, InputStream in, String mimeType,
        String fileName, final long fileSize, Class<V> type) throws IOException {
    HttpPost request = new HttpPost(createV2Uri(uri));
    configureRequest(request);//from   w w w . j  a va2  s  . com

    MultipartEntity entity = new MultipartEntity();
    for (Map.Entry<String, String> entry : stringParts.entrySet())
        entity.addPart(entry.getKey(), StringBody.create(entry.getValue(), "text/plain", UTF_8));

    entity.addPart("file", new InputStreamBody(in, mimeType, fileName) {
        @Override
        public long getContentLength() {
            return fileSize;
        }
    });
    request.setEntity(entity);
    return executeRequest(request, type);
}

From source file:org.s1.testing.httpclient.TestHttpClient.java

/**
 *
 * @param u//from www  .j ava 2  s .c  o m
 * @param data
 * @param name
 * @param contentType
 * @return
 */
public HttpResponseBean uploadFile(String u, InputStream data, String name, String contentType) {
    Map<String, Object> headers = new HashMap<String, Object>();

    u = getURL(u, null);
    HttpPost post = new HttpPost(u);
    try {
        MultipartEntity request = new MultipartEntity();
        ContentBody body = new InputStreamBody(data, contentType, name);
        request.addPart("file", body);
        post.setEntity(request);
        for (String h : headers.keySet()) {
            post.setHeader(h, "" + headers.get(h));
        }

        client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Test Browser");
        client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        //client.getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY);

        HttpResponse resp = null;
        try {
            resp = client.execute(host, post, context);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        Map<String, String> rh = new HashMap<String, String>();
        for (Header h : resp.getAllHeaders()) {
            rh.put(h.getName(), h.getValue());
        }
        try {
            HttpResponseBean r = new HttpResponseBean(resp.getStatusLine().getStatusCode(), rh,
                    EntityUtils.toByteArray(resp.getEntity()));
            printIfError(u, r);
            return r;
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    } finally {
        post.releaseConnection();
    }
}