Example usage for org.apache.http.entity.mime MultipartEntity MultipartEntity

List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity

Introduction

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

Prototype

public MultipartEntity(HttpMultipartMode mode, final String boundary, final Charset charset) 

Source Link

Usage

From source file:com.soundcloud.playerapi.Request.java

/**
 * Builds a request with the given set of parameters and files.
 * @param method    the type of request to use
 * @param <T>       the type of request to use
 * @return HTTP request, prepared to be executed
 *//*from   w  ww  .j a  v  a  2  s  . com*/
public <T extends HttpRequestBase> T buildRequest(Class<T> method) {
    try {
        T request = method.newInstance();
        // POST/PUT ?
        if (request instanceof HttpEntityEnclosingRequestBase) {
            HttpEntityEnclosingRequestBase enclosingRequest = (HttpEntityEnclosingRequestBase) request;

            final Charset charSet = java.nio.charset.Charset.forName(UTF_8);
            if (isMultipart()) {
                MultipartEntity multiPart = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, // XXX change this to STRICT once rack on server is upgraded
                        null, charSet);

                if (mFiles != null) {
                    for (Map.Entry<String, Attachment> e : mFiles.entrySet()) {
                        multiPart.addPart(e.getKey(), e.getValue().toContentBody());
                    }
                }

                for (NameValuePair pair : mParams) {
                    multiPart.addPart(pair.getName(), new StringBody(pair.getValue(), "text/plain", charSet));
                }

                enclosingRequest.setEntity(
                        listener == null ? multiPart : new CountingMultipartEntity(multiPart, listener));

                request.setURI(URI.create(mResource));

                // form-urlencoded?
            } else if (mEntity != null) {
                request.setHeader(mEntity.getContentType());
                enclosingRequest.setEntity(mEntity);
                request.setURI(URI.create(toUrl())); // include the params

            } else {
                if (!mParams.isEmpty()) {
                    request.setHeader("Content-Type", "application/x-www-form-urlencoded");
                    enclosingRequest.setEntity(new StringEntity(queryString()));
                }
                request.setURI(URI.create(mResource));
            }

        } else { // just plain GET/HEAD/DELETE/...
            if (mRange != null) {
                request.addHeader("Range", formatRange(mRange));
            }

            if (mIfNoneMatch != null) {
                request.addHeader("If-None-Match", mIfNoneMatch);
            }
            request.setURI(URI.create(toUrl()));
        }

        if (mToken != null) {
            request.addHeader(ApiWrapper.createOAuthHeader(mToken));
        }
        return request;
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jkan997.slingbeans.slingfs.FileSystemServer.java

public byte[] sendPost(String url, Map<String, Object> changes, Map<String, Object> otherParams) {
    if ((!url.startsWith("http://")) && (!url.startsWith("https://"))) {
        url = serverPrefix + (!url.startsWith("/") ? "/" : "") + url;
    }//from ww w.  j  a v  a 2 s . c o  m
    if (((changes == null) || (changes.isEmpty())) && ((otherParams == null) || (otherParams.isEmpty()))) {
        return null;
    }
    try {
        httpClient = getHttpClient();
        LogHelper.logInfo(this, url);
        StringBuilder diff = new StringBuilder();
        HttpPost post = new HttpPost(url);
        configureAuth(post);
        MultipartEntity reqEntity = new MultipartEntity(null, "slingfs", UTF_8);
        Set<String> skipVals = new TreeSet<String>();
        if ((changes != null) && (!changes.isEmpty())) {
            boolean first = true;
            for (Map.Entry<String, Object> me : changes.entrySet()) {
                String val = ObjectHelper.toString(me.getValue(), "");
                String key = me.getKey();
                if (first) {
                    first = false;
                } else {
                    diff.append("\r\n");
                }
                if (key.startsWith("-")) {
                    skipVals.add(key);
                    diff.append(key + " : " + val);
                } else if (key.startsWith("+")) {
                    diff.append(key + " : \"xxx\"");
                    //skipVals.add(key);
                } else {
                    diff.append("^/" + key + " : ");
                }
            }
            reqEntity.addPart(":diff", new StringBody(diff.toString(), TEXT_PLAIN, UTF_8));
            for (Map.Entry<String, Object> me : changes.entrySet()) {
                String key = me.getKey();
                if (!skipVals.contains(key)) {
                    if ((key.startsWith("^/")) || (key.startsWith("+/"))) {
                        key = key.substring(2);
                    }
                    String jcrPath = "/" + key;
                    reqEntity.addPart(jcrPath, generateBody(me.getKey(), me.getValue()));
                }
            }
        }
        if ((otherParams != null) && (!otherParams.isEmpty())) {
            for (Map.Entry<String, Object> me : otherParams.entrySet()) {
                reqEntity.addPart(me.getKey(), generateBody(me.getKey(), me.getValue()));
            }
        }
        post.setEntity(reqEntity);
        long timeStamp = System.currentTimeMillis();
        dumpHttpRequest(reqEntity, timeStamp);
        HttpResponse response = httpClient.execute(post);
        HttpEntity resEntity = response.getEntity();
        byte[] res = getResponseBytes(resEntity, timeStamp);
        post.releaseConnection();
        return res;
    } catch (Exception ex) {
        LogHelper.logError(ex);
    }
    return null;
}

From source file:com.att.api.rest.RESTClient.java

/**
 * Sends an http POST multipart request.
 *
 * @param jsonObj JSON Object to set as the start part
 * @param fnames file names for any files to add
 * @return api response/*  w  ww.  j  av  a 2 s.  c  o  m*/
 *
 * @throws RESTException if request was unsuccessful
 */
public APIResponse httpPost(JSONObject jsonObj, String[] fnames) throws RESTException {

    HttpResponse response = null;
    try {
        HttpClient httpClient = createClient();

        HttpPost httpPost = new HttpPost(url);
        this.setHeader("Content-Type",
                "multipart/form-data; type=\"application/json\"; " + "start=\"<startpart>\"; boundary=\"foo\"");
        addInternalHeaders(httpPost);

        final Charset encoding = Charset.forName("UTF-8");
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT, "foo", encoding);
        StringBody sbody = new StringBody(jsonObj.toString(), "application/json", encoding);
        FormBodyPart stringBodyPart = new FormBodyPart("root-fields", sbody);
        stringBodyPart.addField("Content-ID", "<startpart>");
        entity.addPart(stringBodyPart);

        for (int i = 0; i < fnames.length; ++i) {
            final String fname = fnames[i];
            String type = URLConnection.guessContentTypeFromStream(new FileInputStream(fname));

            if (type == null) {
                type = URLConnection.guessContentTypeFromName(fname);
            }
            if (type == null) {
                type = "application/octet-stream";
            }

            FileBody fb = new FileBody(new File(fname), type, "UTF-8");
            FormBodyPart fileBodyPart = new FormBodyPart(fb.getFilename(), fb);

            fileBodyPart.addField("Content-ID", "<fileattachment" + i + ">");

            fileBodyPart.addField("Content-Location", fb.getFilename());
            entity.addPart(fileBodyPart);
        }
        httpPost.setEntity(entity);
        return buildResponse(httpClient.execute(httpPost));
    } catch (Exception e) {
        throw new RESTException(e);
    } finally {
        if (response != null) {
            this.releaseConnection(response);
        }
    }
}

From source file:com.att.api.rest.RESTClient.java

public APIResponse httpPost(String[] fnames, String subType, String[] bodyNameAttribute) throws RESTException {
    HttpResponse response = null;/*from  w w  w  . j a  v a2  s.co m*/
    try {
        HttpClient httpClient = createClient();

        HttpPost httpPost = new HttpPost(url);
        this.setHeader("Content-Type", "multipart/" + subType + "; " + "boundary=\"foo\"");
        addInternalHeaders(httpPost);

        final Charset encoding = Charset.forName("UTF-8");
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT, "foo", encoding);

        for (int i = 0; i < fnames.length; ++i) {
            final String fname = fnames[i];
            String contentType = null;
            contentType = URLConnection.guessContentTypeFromStream(new FileInputStream(fname));
            if (contentType == null) {
                contentType = URLConnection.guessContentTypeFromName(fname);
            }
            if (contentType == null)
                contentType = this.getMIMEType(new File(fname));
            if (fname.endsWith("srgs"))
                contentType = "application/srgs+xml";
            if (fname.endsWith("grxml"))
                contentType = "application/srgs+xml";
            if (fname.endsWith("pls"))
                contentType = "application/pls+xml";
            FileBody fb = new FileBody(new File(fname), contentType, "UTF-8");
            FormBodyPart fileBodyPart = new FormBodyPart(bodyNameAttribute[i], fb);
            fileBodyPart.addField("Content-ID", "<fileattachment" + i + ">");
            fileBodyPart.addField("Content-Location", fb.getFilename());
            if (contentType != null) {
                fileBodyPart.addField("Content-Type", contentType);
            }
            entity.addPart(fileBodyPart);
        }
        httpPost.setEntity(entity);
        return buildResponse(httpClient.execute(httpPost));
    } catch (IOException e) {
        throw new RESTException(e);
    } finally {
        if (response != null) {
            this.releaseConnection(response);
        }
    }
}