Search in sources :

Example 1 with InputStreamBody

use of org.apache.http.entity.mime.content.InputStreamBody in project jackrabbit by apache.

the class Utils method addPart.

/**
     *
     * @param paramName
     * @param value
     * @param resolver
     * @throws RepositoryException
     */
static void addPart(String paramName, QValue value, NamePathResolver resolver, List<FormBodyPart> parts, List<QValue> binaries) throws RepositoryException {
    FormBodyPartBuilder builder = FormBodyPartBuilder.create().setName(paramName);
    ContentType ctype = ContentType.create(JcrValueType.contentTypeFromType(value.getType()), DEFAULT_CHARSET);
    FormBodyPart part;
    switch(value.getType()) {
        case PropertyType.BINARY:
            binaries.add(value);
            part = builder.setBody(new InputStreamBody(value.getStream(), ctype)).build();
            break;
        case PropertyType.NAME:
            part = builder.setBody(new StringBody(resolver.getJCRName(value.getName()), ctype)).build();
            break;
        case PropertyType.PATH:
            part = builder.setBody(new StringBody(resolver.getJCRPath(value.getPath()), ctype)).build();
            break;
        default:
            part = builder.setBody(new StringBody(value.getString(), ctype)).build();
    }
    parts.add(part);
}
Also used : FormBodyPart(org.apache.http.entity.mime.FormBodyPart) FormBodyPartBuilder(org.apache.http.entity.mime.FormBodyPartBuilder) ContentType(org.apache.http.entity.ContentType) StringBody(org.apache.http.entity.mime.content.StringBody) InputStreamBody(org.apache.http.entity.mime.content.InputStreamBody)

Example 2 with InputStreamBody

use of org.apache.http.entity.mime.content.InputStreamBody in project weixin-java-tools by chanjarster.

the class MaterialUploadRequestExecutor method execute.

public WxMpMaterialUploadResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, WxMpMaterial material) throws WxErrorException, ClientProtocolException, IOException {
    HttpPost httpPost = new HttpPost(uri);
    if (httpProxy != null) {
        RequestConfig response = RequestConfig.custom().setProxy(httpProxy).build();
        httpPost.setConfig(response);
    }
    if (material != null) {
        File file = material.getFile();
        if (file == null || !file.exists()) {
            throw new FileNotFoundException();
        }
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addPart("media", new InputStreamBody(bufferedInputStream, material.getName())).setMode(HttpMultipartMode.RFC6532);
        Map<String, String> form = material.getForm();
        if (material.getForm() != null) {
            multipartEntityBuilder.addTextBody("description", WxGsonBuilder.create().toJson(form));
        }
        httpPost.setEntity(multipartEntityBuilder.build());
        httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
    }
    CloseableHttpResponse response = httpclient.execute(httpPost);
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    WxError error = WxError.fromJson(responseContent);
    if (error.getErrorCode() != 0) {
        throw new WxErrorException(error);
    } else {
        return WxMpMaterialUploadResult.fromJson(responseContent);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) WxError(me.chanjar.weixin.common.bean.result.WxError) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) WxErrorException(me.chanjar.weixin.common.exception.WxErrorException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) InputStreamBody(org.apache.http.entity.mime.content.InputStreamBody)

Example 3 with InputStreamBody

use of org.apache.http.entity.mime.content.InputStreamBody in project AndroidSDK-RecipeBook by gabu.

the class Recipe095 method uploadForTumblr.

// 指定されたUriの写真をTumblrにアップロードします。
private void uploadForTumblr(Uri uri) {
    // HTTPクライアントを作って
    HttpClient client = new DefaultHttpClient();
    // POST先のURLを指定してPOSTオブジェクトを作って
    HttpPost post = new HttpPost("http://www.tumblr.com/api/write");
    // パラメータを作って
    MultipartEntity entity = new MultipartEntity();
    try {
        // Thumblrに登録したメールアドレス
        entity.addPart("email", new StringBody("hoge@example.com"));
        // Thumblrに登録したパスワード
        entity.addPart("password", new StringBody("1234"));
        // 投稿する種類。今回は写真なのでphoto
        entity.addPart("type", new StringBody("photo"));
        // 写真データ
        entity.addPart("data", new InputStreamBody(getContentResolver().openInputStream(uri), "filename"));
        // POSTオブジェクトにパラメータをセット
        post.setEntity(entity);
        // POSTリクエストを実行
        client.execute(post);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) FileNotFoundException(java.io.FileNotFoundException) InputStreamBody(org.apache.http.entity.mime.content.InputStreamBody) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 4 with InputStreamBody

use of org.apache.http.entity.mime.content.InputStreamBody in project lucene-solr by apache.

the class HttpSolrClient method createMethod.

protected HttpRequestBase createMethod(final SolrRequest request, String collection) throws IOException, SolrServerException {
    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);
    }
    String basePath = baseUrl;
    if (collection != null)
        basePath += "/" + collection;
    if (request instanceof V2Request) {
        if (System.getProperty("solr.v2RealPath") == null) {
            basePath = baseUrl.replace("/solr", "/v2");
        } else {
            basePath = baseUrl + "/____v2";
        }
    }
    if (SolrRequest.METHOD.GET == request.getMethod()) {
        if (streams != null) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
        }
        return new HttpGet(basePath + path + wparams.toQueryString());
    }
    if (SolrRequest.METHOD.DELETE == request.getMethod()) {
        return new HttpDelete(basePath + path + wparams.toQueryString());
    }
    if (SolrRequest.METHOD.POST == request.getMethod() || SolrRequest.METHOD.PUT == request.getMethod()) {
        String url = basePath + path;
        boolean hasNullStreamName = false;
        if (streams != null) {
            for (ContentStream cs : streams) {
                if (cs.getName() == null) {
                    hasNullStreamName = true;
                    break;
                }
            }
        }
        boolean isMultipart = ((this.useMultiPartPost && SolrRequest.METHOD.POST == request.getMethod()) || (streams != null && streams.size() > 1)) && !hasNullStreamName;
        LinkedList<NameValuePair> postOrPutParams = new LinkedList<>();
        if (streams == null || isMultipart) {
            // send server list and request list as query string params
            ModifiableSolrParams queryParams = calculateQueryParams(this.queryParams, wparams);
            queryParams.add(calculateQueryParams(request.getQueryParams(), wparams));
            String fullQueryUrl = url + queryParams.toQueryString();
            HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod() ? new HttpPost(fullQueryUrl) : new HttpPut(fullQueryUrl);
            if (!isMultipart) {
                postOrPut.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            }
            List<FormBodyPart> parts = new LinkedList<>();
            Iterator<String> iter = wparams.getParameterNamesIterator();
            while (iter.hasNext()) {
                String p = iter.next();
                String[] vals = wparams.getParams(p);
                if (vals != null) {
                    for (String v : vals) {
                        if (isMultipart) {
                            parts.add(new FormBodyPart(p, new StringBody(v, StandardCharsets.UTF_8)));
                        } else {
                            postOrPutParams.add(new BasicNameValuePair(p, v));
                        }
                    }
                }
            }
            // TODO: remove deprecated - first simple attempt failed, see {@link MultipartEntityBuilder}
            if (isMultipart && streams != null) {
                for (ContentStream content : streams) {
                    String contentType = content.getContentType();
                    if (contentType == null) {
                        // default
                        contentType = BinaryResponseParser.BINARY_CONTENT_TYPE;
                    }
                    String name = content.getName();
                    if (name == null) {
                        name = "";
                    }
                    parts.add(new FormBodyPart(name, new InputStreamBody(content.getStream(), contentType, content.getName())));
                }
            }
            if (parts.size() > 0) {
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);
                for (FormBodyPart p : parts) {
                    entity.addPart(p);
                }
                postOrPut.setEntity(entity);
            } else {
                //not using multipart
                postOrPut.setEntity(new UrlEncodedFormEntity(postOrPutParams, StandardCharsets.UTF_8));
            }
            return postOrPut;
        } else // It is has one stream, it is the post body, put the params in the URL
        {
            String fullQueryUrl = url + wparams.toQueryString();
            HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod() ? new HttpPost(fullQueryUrl) : new HttpPut(fullQueryUrl);
            // 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) {
                Long size = contentStream[0].getSize();
                postOrPut.setEntity(new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) {

                    @Override
                    public Header getContentType() {
                        return new BasicHeader("Content-Type", contentStream[0].getContentType());
                    }

                    @Override
                    public boolean isRepeatable() {
                        return false;
                    }
                });
            } else {
                Long size = contentStream[0].getSize();
                postOrPut.setEntity(new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) {

                    @Override
                    public Header getContentType() {
                        return new BasicHeader("Content-Type", contentStream[0].getContentType());
                    }

                    @Override
                    public boolean isRepeatable() {
                        return false;
                    }
                });
            }
            return postOrPut;
        }
    }
    throw new SolrServerException("Unsupported method: " + request.getMethod());
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ResponseParser(org.apache.solr.client.solrj.ResponseParser) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpGet(org.apache.http.client.methods.HttpGet) SolrServerException(org.apache.solr.client.solrj.SolrServerException) ModifiableSolrParams(org.apache.solr.common.params.ModifiableSolrParams) HttpPut(org.apache.http.client.methods.HttpPut) FormBodyPart(org.apache.http.entity.mime.FormBodyPart) ContentStream(org.apache.solr.common.util.ContentStream) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) InputStreamBody(org.apache.http.entity.mime.content.InputStreamBody) SolrException(org.apache.solr.common.SolrException) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) V2Request(org.apache.solr.client.solrj.request.V2Request) LinkedList(java.util.LinkedList) InputStreamEntity(org.apache.http.entity.InputStreamEntity) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) StringBody(org.apache.http.entity.mime.content.StringBody) SolrParams(org.apache.solr.common.params.SolrParams) ModifiableSolrParams(org.apache.solr.common.params.ModifiableSolrParams) BasicHeader(org.apache.http.message.BasicHeader)

Example 5 with InputStreamBody

use of org.apache.http.entity.mime.content.InputStreamBody in project sling by apache.

the class SlingSpecificsSightlyIT method uploadFile.

private void uploadFile(String fileName, String serverFileName, String url) throws IOException {
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(launchpadURL + url);
    post.setHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    InputStreamBody inputStreamBody = new InputStreamBody(this.getClass().getClassLoader().getResourceAsStream(fileName), ContentType.TEXT_PLAIN, fileName);
    entityBuilder.addPart(serverFileName, inputStreamBody);
    post.setEntity(entityBuilder.build());
    httpClient.execute(post);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) InputStreamBody(org.apache.http.entity.mime.content.InputStreamBody)

Aggregations

InputStreamBody (org.apache.http.entity.mime.content.InputStreamBody)7 HttpPost (org.apache.http.client.methods.HttpPost)4 StringBody (org.apache.http.entity.mime.content.StringBody)4 MultipartEntity (org.apache.http.entity.mime.MultipartEntity)3 MultipartEntityBuilder (org.apache.http.entity.mime.MultipartEntityBuilder)3 HttpClient (org.apache.http.client.HttpClient)2 ContentType (org.apache.http.entity.ContentType)2 FormBodyPart (org.apache.http.entity.mime.FormBodyPart)2 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)2 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 OutputStreamWriter (java.io.OutputStreamWriter)1 Reader (java.io.Reader)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 Writer (java.io.Writer)1 Charset (java.nio.charset.Charset)1 LinkedHashMap (java.util.LinkedHashMap)1 LinkedList (java.util.LinkedList)1