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

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

Introduction

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

Prototype

public void addPart(final String name, final ContentBody contentBody) 

Source Link

Usage

From source file:org.xmetdb.rest.protocol.CallableProtocolUpload.java

protected HttpEntity createPOSTEntity(DBAttachment attachment) throws Exception {
    Charset utf8 = Charset.forName("UTF-8");

    if ("text/uri-list".equals(attachment.getFormat())) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("title", attachment.getProtocol().getIdentifier()));
        formparams.add(new BasicNameValuePair("dataset_uri", attachment.getDescription()));
        formparams.add(new BasicNameValuePair("folder",
                attachment_type.substrate.equals(attachment.getType()) ? "substrate" : "product"));
        return new UrlEncodedFormEntity(formparams, "UTF-8");
    } else {//  w w  w . j  av  a2 s.  c  o m
        if (attachment.getResourceURL() == null)
            throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Attachment resource URL is null! ");
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, utf8);
        entity.addPart("title", new StringBody(attachment.getTitle(), utf8));
        entity.addPart("seeAlso", new StringBody(attachment.getDescription(), utf8));
        entity.addPart("license", new StringBody("XMETDB", utf8));
        URI uri = attachment.getResourceURL().toURI();
        entity.addPart("file", new FileBody(new File(uri)));
        return entity;
    }
    //match, seeAlso, license
}

From source file:com.mobisys.android.ibp.ObservationRequestQueue.java

private void uploadImage(final boolean single, final Bundle b, final Context context,
        final ArrayList<String> imageStringPath, ArrayList<String> imageType, final ObservationInstance sp) {
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    if (b != null)
        Log.d("ObservationRequestQueue", "Params: " + b.toString());
    int countUri = 0;
    for (int i = 0; i < imageStringPath.size(); i++) {
        if (!imageStringPath.get(i).contains("http://")) {
            FileBody bab;//from w ww  .j  a v a2  s  .  com
            if (imageType.get(i) != null)
                bab = new FileBody(new File(imageStringPath.get(i)), imageType.get(i)); // image path and image type
            else
                bab = new FileBody(new File(imageStringPath.get(i)), "image/jpeg"); // image p   
            reqEntity.addPart("resources", bab);

            ++countUri;
        }
    }

    // if imagestring path has no Image url's.
    if (countUri != 0) {
        try {
            reqEntity.addPart(Request.RESOURCE_TYPE, new StringBody("species.participation.Observation"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        WebService.sendMultiPartRequest(context, Request.METHOD_POST, Request.PATH_UPLOAD_RESOURCE,
                new ResponseHandler() {

                    @Override
                    public void onSuccess(String response) {
                        sp.setStatus(StatusType.PROCESSING);
                        ObservationInstanceTable.updateRowFromTable(context, sp);
                        parseUploadResourceDetail(response, single, b, context, sp, imageStringPath);
                    }

                    @Override
                    public void onFailure(Throwable e, String content) {
                        Log.d("NetWorkState", content);
                        if (e instanceof UnknownHostException || e instanceof ConnectException) {
                            mIsRunning = false;
                            return;
                        }
                        sp.setStatus(StatusType.FAILURE);
                        sp.setMessage(content);
                        ObservationInstanceTable.updateRowFromTable(context, sp);
                        //ObservationParamsTable.deleteRowFromTable(context, sp);
                        if (!single) {
                            ObservationInstance sp_new = ObservationInstanceTable.getFirstRecord(context);
                            observationMethods(single, sp_new, context);
                        }
                    }
                }, reqEntity);

    } else { // if all are url's
        for (int i = 0; i < imageStringPath.size(); i++) {
            b.putString("file_" + (i + 1), imageStringPath.get(i)
                    .replace("http://" + HttpUtils.stageOrProdBaseURL() + "/biodiv/observations/", ""));
            b.putString("type_" + (i + 1), Constants.IMAGE);
            b.putString("license_" + (i + 1), "CC_BY");
        }
        submitObservationRequestFinally(single, b, context, sp);
    }
}

From source file:org.votingsystem.util.HttpHelper.java

public ResponseVS sendObjectMap(Map<String, Object> fileMap, String serverURL) throws Exception {
    log.info("sendObjectMap - serverURL: " + serverURL);
    ResponseVS responseVS = null;/*  w ww . ja va 2 s .  c o  m*/
    if (fileMap == null || fileMap.isEmpty())
        throw new Exception(ContextVS.getInstance().getMessage("requestWithoutFileMapErrorMsg"));
    HttpPost httpPost = null;
    CloseableHttpResponse response = null;
    ContentTypeVS responseContentType = null;
    try {
        httpPost = new HttpPost(serverURL);
        Set<String> fileNames = fileMap.keySet();
        MultipartEntity reqEntity = new MultipartEntity();
        for (String objectName : fileNames) {
            Object objectToSend = fileMap.get(objectName);
            if (objectToSend instanceof File) {
                File file = (File) objectToSend;
                log.info("sendObjectMap - fileName: " + objectName + " - filePath: " + file.getAbsolutePath());
                FileBody fileBody = new FileBody(file);
                reqEntity.addPart(objectName, fileBody);
            } else if (objectToSend instanceof byte[]) {
                byte[] byteArray = (byte[]) objectToSend;
                reqEntity.addPart(objectName, new ByteArrayBody(byteArray, objectName));
            }
        }
        httpPost.setEntity(reqEntity);
        response = httpClient.execute(httpPost);
        Header header = response.getFirstHeader("Content-Type");
        if (header != null)
            responseContentType = ContentTypeVS.getByName(header.getValue());
        log.info("----------------------------------------");
        log.info(response.getStatusLine().toString() + " - contentTypeVS: " + responseContentType
                + " - connManager stats: " + connManager.getTotalStats().toString());
        log.info("----------------------------------------");
        byte[] responseBytes = EntityUtils.toByteArray(response.getEntity());
        responseVS = new ResponseVS(response.getStatusLine().getStatusCode(), responseBytes,
                responseContentType);
        EntityUtils.consume(response.getEntity());
    } catch (Exception ex) {
        String statusLine = null;
        if (response != null)
            statusLine = response.getStatusLine().toString();
        log.log(Level.SEVERE, ex.getMessage() + " - StatusLine: " + statusLine, ex);
        responseVS = new ResponseVS(ResponseVS.SC_ERROR, ex.getMessage());
        if (httpPost != null)
            httpPost.abort();
    } finally {
        try {
            if (response != null)
                response.close();
        } catch (Exception ex) {
            log.log(Level.SEVERE, ex.getMessage(), ex);
        }
        return responseVS;
    }
}

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

@Override
public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException {
    try {/*www.j av  a 2 s.  com*/
        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:org.mumod.util.HttpManager.java

private InputStream requestData(String url, ArrayList<NameValuePair> params, String attachmentParam,
        File attachment) throws IOException, MustardException, AuthException {

    URI uri;/*from   w w w  .  j  a v a2  s  . c o m*/

    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid URL.");
    }
    if (MustardApplication.DEBUG)
        Log.d("HTTPManager", "Requesting " + uri);

    HttpPost post = new HttpPost(uri);

    HttpResponse response;

    // create the multipart request and add the parts to it 
    MultipartEntity requestContent = new MultipartEntity();
    long len = attachment.length();

    InputStream ins = new FileInputStream(attachment);
    InputStreamEntity ise = new InputStreamEntity(ins, -1L);
    byte[] data = EntityUtils.toByteArray(ise);

    String IMAGE_MIME = attachment.getName().toLowerCase().endsWith("png") ? IMAGE_MIME_PNG : IMAGE_MIME_JPG;
    requestContent.addPart(attachmentParam, new ByteArrayBody(data, IMAGE_MIME, attachment.getName()));

    if (params != null) {
        for (NameValuePair param : params) {
            len += param.getValue().getBytes().length;
            requestContent.addPart(param.getName(), new StringBody(param.getValue()));
        }
    }
    post.setEntity(requestContent);

    Log.d("Mustard", "Length: " + len);

    if (mHeaders != null) {
        Iterator<String> headKeys = mHeaders.keySet().iterator();
        while (headKeys.hasNext()) {
            String key = headKeys.next();
            post.setHeader(key, mHeaders.get(key));
        }
    }

    if (consumer != null) {
        try {
            consumer.sign(post);
        } catch (OAuthMessageSignerException e) {

        } catch (OAuthExpectationFailedException e) {

        } catch (OAuthCommunicationException e) {

        }
    }

    try {
        mClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,
                DEFAULT_POST_REQUEST_TIMEOUT);
        mClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT);
        response = mClient.execute(post);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new IOException("HTTP protocol error.");
    }

    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode == 401) {
        throw new AuthException(401, "Unauthorized: " + url);
    } else if (statusCode == 400 || statusCode == 403 || statusCode == 406) {
        try {
            JSONObject json = null;
            try {
                json = new JSONObject(StreamUtil.toString(response.getEntity().getContent()));
            } catch (JSONException e) {
                throw new MustardException(998, "Non json response: " + e.toString());
            }
            throw new MustardException(statusCode, json.getString("error"));
        } catch (IllegalStateException e) {
            throw new IOException("Could not parse error response.");
        } catch (JSONException e) {
            throw new IOException("Could not parse error response.");
        }
    } else if (statusCode != 200) {
        Log.e("Mustard", response.getStatusLine().getReasonPhrase());
        throw new MustardException(999, "Unmanaged response code: " + statusCode);
    }

    return response.getEntity().getContent();
}

From source file:ua.pp.msk.gradle.http.Client.java

public boolean upload(NexusConf nc) throws ArtifactPromotionException {
    boolean result = false;
    String possibleFailReason = "Unknown";
    try {//from ww w . ja  va  2 s. c  o m
        HttpPost httpPost = new HttpPost(targetUrl.toString());

        MultipartEntity me = new MultipartEntity(HttpMultipartMode.STRICT);
        //            FormBodyPart fbp = new FormBodyPart("form", new StringBody("check it"));
        //            fbp.addField("r", nc.getRepository());
        //            fbp.addField("hasPom", "" + nc.isHasPom());
        //            fbp.addField("e", nc.getExtension());
        //            fbp.addField("g", nc.getGroup());
        //            fbp.addField("a", nc.getArtifact());
        //            fbp.addField("v", nc.getVersion());
        //            fbp.addField("p", nc.getPackaging());
        //            me.addPart(fbp);
        File rpmFile = new File(nc.getFile());
        ContentBody cb = new FileBody(rpmFile);
        me.addPart("p", new StringBody(nc.getPackaging()));
        me.addPart("e", new StringBody(nc.getExtension()));
        me.addPart("r", new StringBody(nc.getRepository()));
        me.addPart("g", new StringBody(nc.getGroup()));
        me.addPart("a", new StringBody(nc.getArtifact()));
        me.addPart("v", new StringBody(nc.getVersion()));
        me.addPart("c", new StringBody(nc.getClassifier()));
        me.addPart("file", cb);

        httpPost.setHeader("User-Agent", userAgent);
        httpPost.setEntity(me);

        logger.debug("Sending request");
        HttpResponse postResponse = client.execute(httpPost, context);
        logger.debug("Status line: " + postResponse.getStatusLine().toString());
        int statusCode = postResponse.getStatusLine().getStatusCode();

        HttpEntity entity = postResponse.getEntity();

        try (BufferedReader bufReader = new BufferedReader(new InputStreamReader(entity.getContent()))) {
            StringBuilder fsb = new StringBuilder();
            bufReader.lines().forEach(e -> {
                logger.debug(e);
                fsb.append(e);
                fsb.append("\n");
            });
            possibleFailReason = fsb.toString();
        } catch (IOException ex) {
            logger.warn("Cannot get entity response", ex);
        }

        switch (statusCode) {
        case 200:
            logger.debug("Got a successful http response " + postResponse.getStatusLine());
            result = true;
            break;
        case 201:
            logger.debug("Created! Got a successful http response " + postResponse.getStatusLine());
            result = true;
            break;
        case 401:
            throw new BadCredentialsException(
                    "Bad credentials. Response status: " + postResponse.getStatusLine());
        default:
            throw new ResponseException(
                    String.format("Response is not OK. Response status: %s\n\tPossible reason: %s",
                            postResponse.getStatusLine(), possibleFailReason));
        }

        EntityUtils.consume(entity);

    } catch (UnsupportedEncodingException ex) {
        logger.error("Encoding is unsuported ", ex);
        throw new ArtifactPromotionException("Encoding is unsuported " + ex.getMessage());
    } catch (IOException ex) {
        logger.error("Got IO excepption ", ex);
        throw new ArtifactPromotionException("Input/Output error " + ex.getMessage());
    } catch (ResponseException | BadCredentialsException ex) {
        logger.error("Cannot upload artifact", ex);
        throw new ArtifactPromotionException("Cannot upload artifact " + ex.getMessage());
    }
    return result;
}

From source file:org.mustard.util.HttpManager.java

private InputStream requestData(String url, ArrayList<NameValuePair> params, String attachmentParam,
        File attachment) throws IOException, MustardException, AuthException {

    URI uri;//from w w  w . j av a  2 s .c o  m

    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid URL.");
    }
    if (MustardApplication.DEBUG)
        Log.d("HTTPManager", "Requesting " + uri);

    HttpPost post = new HttpPost(uri);

    HttpResponse response;

    // create the multipart request and add the parts to it 
    MultipartEntity requestContent = new MultipartEntity();
    long len = attachment.length();

    InputStream ins = new FileInputStream(attachment);
    InputStreamEntity ise = new InputStreamEntity(ins, -1L);
    byte[] data = EntityUtils.toByteArray(ise);

    String IMAGE_MIME = attachment.getName().toLowerCase().endsWith("png") ? IMAGE_MIME_PNG : IMAGE_MIME_JPG;
    requestContent.addPart(attachmentParam, new ByteArrayBody(data, IMAGE_MIME, attachment.getName()));

    if (params != null) {
        for (NameValuePair param : params) {
            len += param.getValue().getBytes().length;
            requestContent.addPart(param.getName(), new StringBody(param.getValue()));
        }
    }
    post.setEntity(requestContent);

    Log.d("Mustard", "Length: " + len);

    if (mHeaders != null) {
        Iterator<String> headKeys = mHeaders.keySet().iterator();
        while (headKeys.hasNext()) {
            String key = headKeys.next();
            post.setHeader(key, mHeaders.get(key));
        }
    }

    if (consumer != null) {
        try {
            consumer.sign(post);
        } catch (OAuthMessageSignerException e) {

        } catch (OAuthExpectationFailedException e) {

        } catch (OAuthCommunicationException e) {

        }
    }

    try {
        mClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,
                DEFAULT_POST_REQUEST_TIMEOUT);
        mClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT);
        response = mClient.execute(post);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new IOException("HTTP protocol error.");
    }

    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode == 401) {
        throw new AuthException(401, "Unauthorized: " + url);
    } else if (statusCode == 403 || statusCode == 406) {
        try {
            JSONObject json = null;
            try {
                json = new JSONObject(StreamUtil.toString(response.getEntity().getContent()));
            } catch (JSONException e) {
                throw new MustardException(998, "Non json response: " + e.toString());
            }
            throw new MustardException(statusCode, json.getString("error"));
        } catch (IllegalStateException e) {
            throw new IOException("Could not parse error response.");
        } catch (JSONException e) {
            throw new IOException("Could not parse error response.");
        }
    } else if (statusCode != 200) {
        Log.e("Mustard", response.getStatusLine().getReasonPhrase());
        throw new MustardException(999, "Unmanaged response code: " + statusCode);
    }

    return response.getEntity().getContent();
}

From source file:org.openestate.is24.restapi.hc42.HttpComponents42Client.java

@Override
protected Response sendVideoUploadRequest(URL url, RequestMethod method, String auth, InputStream input,
        String fileName, final long fileSize) throws IOException, OAuthException {
    if (method == null)
        method = RequestMethod.POST;/*  www . j a v  a2s.com*/
    if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method))
        throw new IllegalArgumentException("Invalid request method!");

    HttpUriRequest request = null;
    if (RequestMethod.POST.equals(method)) {
        request = new HttpPost(url.toString());
    } else if (RequestMethod.PUT.equals(method)) {
        request = new HttpPut(url.toString());
    } else {
        throw new IOException("Unsupported request method '" + method + "'!");
    }

    MultipartEntity requestMultipartEntity = new MultipartEntity();
    request.setHeader("MIME-Version", "1.0");
    request.addHeader(requestMultipartEntity.getContentType());
    request.setHeader("Content-Language", "en-US");
    request.setHeader("Accept-Charset", "UTF-8");
    request.setHeader("Accept-Encoding", "gzip,deflate");
    request.setHeader("Connection", "close");

    // add auth part to the multipart entity
    auth = StringUtils.trimToNull(auth);
    if (auth != null) {
        StringBody authPart = new StringBody(auth, Charset.forName(getEncoding()));
        requestMultipartEntity.addPart("auth", authPart);
    }

    // add file part to the multipart entity
    if (input != null) {
        fileName = StringUtils.trimToNull(fileName);
        if (fileName == null)
            fileName = "upload.bin";
        //InputStreamBody filePart = new InputStreamBody( input, fileName );
        InputStreamBody filePart = new InputStreamBodyWithLength(input, fileName, fileSize);
        requestMultipartEntity.addPart("videofile", filePart);
    }

    // add multipart entity to the request
    ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity);

    // sign request
    //getAuthConsumer().sign( request );

    // send request
    HttpResponse response = httpClient.execute(request);

    // create response
    return createResponse(response);
}

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
 *///  w w  w  .  j a  v  a2s. co m
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:li.zeitgeist.api.ZeitgeistApi.java

public List<Item> createByFiles(List<File> files, String tags, boolean announce, OnProgressListener listener)
        throws ZeitgeistError {
    MultipartEntity entity;
    if (listener == null) {
        entity = new MultipartEntity();
    } else {/*from  w ww.  j  a  v  a 2  s.  c  o m*/
        entity = new MultipartEntityWithProgress(listener);
    }

    for (File file : files) {
        entity.addPart("image_upload[]", new FileBody(file));
    }

    try {
        entity.addPart("tags", new StringBody(tags));
        entity.addPart("announce", new StringBody(announce ? "true" : "false"));
    } catch (UnsupportedEncodingException e) {
        throw new ZeitgeistError("UnsupportedEncoding: " + e.getMessage());
    }

    Map<String, ?> jsonObject = postRequest("/new", entity);

    ArrayList<Map<String, ?>> itemObjects = (ArrayList<Map<String, ?>>) jsonObject.get("items");

    List<Item> items = new Vector<Item>();
    for (Map<String, ?> itemObject : itemObjects) {
        items.add(new Item(itemObject, baseUrl));
    }

    return items;
}