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(final HttpMultipartMode mode) 

Source Link

Usage

From source file:org.apache.hadoop.hdfs.qjournal.client.HttpImageUploadChannel.java

/**
 * Create a post request encapsulating bytes from the given
 * ByteArrayOutputStream./*from   w  w w  .j a  v a2 s  . c o m*/
 */
private HttpPost setupRequest(ByteArrayOutputStream bos) {
    ContentBody cb = new ByteArrayBody(bos.toByteArray(), "image");
    HttpPost postRequest = new HttpPost(uri + "/uploadImage");
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    // add a single part to the request
    reqEntity.addPart("file", cb);
    postRequest.setEntity(reqEntity);

    return postRequest;
}

From source file:com.wishlist.Wishlist.java

public void uploadPhoto() {
    uploadCancelled = false;/*from  w  ww .j av a2 s  . c  o m*/
    dialog = ProgressDialog.show(Wishlist.this, "", getString(R.string.uploading_photo), true, true,
            new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    uploadCancelled = true;
                }
            });

    /*
     * Upload photo to the server in a new thread
     */
    new Thread() {
        public void run() {
            try {
                String postURL = HOST_SERVER_URL + HOST_PHOTO_UPLOAD_URI;

                HttpClient httpClient = new DefaultHttpClient();
                HttpPost postRequest = new HttpPost(postURL);

                ByteArrayBody bab = new ByteArrayBody(imageBytes, "file_name_ignored");
                MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                reqEntity.addPart("source", bab);
                postRequest.setEntity(reqEntity);

                HttpResponse response = httpClient.execute(postRequest);
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                String sResponse;
                StringBuilder s = new StringBuilder();
                while ((sResponse = reader.readLine()) != null) {
                    s = s.append(sResponse);
                }
                /*
                 * JSONObject is returned with image_name and image_url
                 */
                JSONObject jsonResponse = new JSONObject(s.toString());
                mProductImageName = jsonResponse.getString("image_name");
                mProductImageURL = jsonResponse.getString("image_url");
                dismissDialog();
                if (mProductImageName == null) {
                    showToast(getString(R.string.error_uploading_photo));
                    return;
                }
                /*
                 * photo upload finish, now publish to the timeline
                 */
                if (!uploadCancelled) {
                    mHandler.post(new Runnable() {
                        public void run() {
                            addToTimeline();
                        }
                    });
                }
            } catch (Exception e) {
                Log.e(e.getClass().getName(), e.getMessage());
            }
        }
    }.start();
}

From source file:truesculpt.ui.panels.WebFilePanel.java

private void uploadPicture(File imagefile, File zipobjectfile, String uploadURL, String title,
        String description) throws ParseException, IOException, URISyntaxException {
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(uploadURL);
    httppost.addHeader("title", title);
    httppost.addHeader("description", description);
    httppost.addHeader("installationID", UtilsManager.Installation.id(this));

    MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.STRICT);
    ContentBody cbImageFile = new FileBody(imagefile, "image/png");
    ContentBody cbObjectFile = new FileBody(zipobjectfile, "application/zip");

    mpEntity.addPart("imagefile", cbImageFile);
    mpEntity.addPart("objectfile", cbObjectFile);

    httppost.setEntity(mpEntity);//from www.j  av a 2s. com

    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse httpResponse = httpclient.execute(httppost);

    String myHeader = "displayURL";
    Header[] headers = httpResponse.getHeaders(myHeader);
    for (int i = 0; i < headers.length; i++) {
        Header header = headers[i];
        if (header.getName().equals(myHeader)) {
            String newURL = mStrBaseWebSite + header.getValue();
            Log.d("WEB", "Loading web site " + newURL);
            mWebView.loadUrl(newURL);
        }
    }

}

From source file:ecblast.test.EcblastTest.java

public String compareReactions(String queryFormat, String query, String targetFormat, String target)
        throws Exception {
    DefaultHttpClient client;//from  w w  w . ja va2  s.co m
    client = new DefaultHttpClient();
    String urlString = "http://localhost:8080/ecblast-rest/compare";
    HttpPost postRequest = new HttpPost(urlString);
    try {
        //Set various attributes
        MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        //multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : ""));
        //multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName()));
        switch (queryFormat) {
        case "RXN":
            FileBody fileBody = new FileBody(new File(query));
            //Prepare payload
            multiPartEntity.addPart("q", fileBody);
            multiPartEntity.addPart("Q", new StringBody("RXN", "text/plain", Charset.forName("UTF-8")));
            break;
        case "SMI":
            multiPartEntity.addPart("q", new StringBody(query, "text/plain", Charset.forName("UTF-8")));
            multiPartEntity.addPart("Q", new StringBody("SMI", "text/plain", Charset.forName("UTF-8")));
            break;
        }
        switch (targetFormat) {
        case "RXN":
            FileBody fileBody = new FileBody(new File(target));
            //Prepare payload
            multiPartEntity.addPart("t", fileBody);
            multiPartEntity.addPart("T", new StringBody("RXN", "text/plain", Charset.forName("UTF-8")));
            break;
        case "SMI":
            multiPartEntity.addPart("t", new StringBody(target, "text/plain", Charset.forName("UTF-8")));
            multiPartEntity.addPart("T", new StringBody("SMI", "text/plain", Charset.forName("UTF-8")));
            break;
        }

        //Set to request body
        postRequest.setEntity(multiPartEntity);

        //Send request
        HttpResponse response = client.execute(postRequest);

        //Verify response if any
        if (response != null) {
            System.out.println(response.getStatusLine().getStatusCode());
            return response.toString();
        }
    } catch (IOException ex) {
    }
    return null;
}

From source file:com.google.cloud.solutions.smashpix.MainActivity.java

  /**
 * Uploads the image to Google Cloud Storage.
 *///from   ww  w  .  j  a v  a 2  s  . com
public Boolean uploadToCloudStorage(ServicesStorageSignedUrlResponse signedUrlParams,
  File localImageStoragePath){
  if (!signedUrlParams.isEmpty() && localImageStoragePath.exists())  {
    FileBody binary = new FileBody(localImageStoragePath);
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(signedUrlParams.getFormAction());
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    try {
      entity.addPart("bucket", new StringBody(signedUrlParams.getBucket()));
      entity.addPart("key", new StringBody(signedUrlParams.getFilename()));
      entity.addPart("policy", new StringBody(signedUrlParams.getPolicy()));
      entity.addPart("signature", new StringBody(signedUrlParams.getSignature()));
      entity.addPart("x-goog-meta-owner", new StringBody(accountName));
      entity.addPart("GoogleAccessId", new StringBody(signedUrlParams.getGoogleAccessId()));
      entity.addPart("file", binary);
    } catch (UnsupportedEncodingException e) {
      Log.e(Constants.APP_NAME, e.getMessage());
      return false;
    }

    httpPost.setEntity(entity);
    HttpResponse httpResponse;
    try {
      httpResponse = httpClient.execute(httpPost);
      if (httpResponse.getStatusLine().getStatusCode() == 204) {
        Log.i(Constants.APP_NAME, "Image Uploaded");
        return true;
      }
    } catch (ClientProtocolException e) {
        Log.e(Constants.APP_NAME, e.getMessage());
    } catch (IOException e) {
        Log.e(Constants.APP_NAME, e.getMessage());
    }
  }
  Log.e(Constants.APP_NAME, "Image Upload Failed");
  return false;
}

From source file:org.hyperic.hq.hqapi1.HQConnection.java

/**
 * Issue a POST against the API./*ww  w.  j a v  a2s  .c o m*/
 * 
 * @param path
 *            The web service endpoint
 * @param params
 *            A Map of key value pairs that are added to the post data
 * @param file
 *            The file to post
 * @param responseHandler
 *            The {@link org.hyperic.hq.hqapi1.ResponseHandler} to handle this response.
 * @return The response object from the operation. This response will be of
 *         the type given in the responseHandler argument.
 * @throws IOException
 *             If a network error occurs during the request.
 */
public <T> T doPost(String path, Map<String, String> params, File file, ResponseHandler<T> responseHandler)
        throws IOException {
    HttpPost post = new HttpPost();
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    multipartEntity.addPart(file.getName(), new FileBody(file));

    for (Map.Entry<String, String> paramEntry : params.entrySet()) {
        multipartEntity.addPart(new FormBodyPart(paramEntry.getKey(), new StringBody(paramEntry.getValue())));
    }

    post.setEntity(multipartEntity);

    return runMethod(post, path, responseHandler);
}

From source file:com.dropbox.client.DropboxClient.java

/**
 * Put a file in the user's Dropbox./*from  w w  w . j  av  a  2  s  .com*/
 */
public HttpResponse putFile(String root, String to_path, File file_obj) throws DropboxException {
    String path = "/files/" + root + to_path;

    HttpClient client = getClient();

    try {
        String target = buildFullURL(secureProtocol, content_host, this.port,
                buildURL(path, API_VERSION, null));
        HttpPost req = new HttpPost(target);
        // this has to be done this way because of how oauth signs params
        // first we add a "fake" param of file=path of *uploaded* file
        // THEN we sign that.
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("file", file_obj.getName()));
        req.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        consumer.sign(req);

        // now we can add the real file multipart and we're good
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        FileBody bin = new FileBody(file_obj);
        entity.addPart("file", bin);
        // this resets it to the new entity with the real file
        req.setEntity(entity);

        HttpResponse resp = client.execute(req);

        resp.getEntity().consumeContent();
        return resp;
    } catch (Exception e) {
        throw new DropboxException(e);
    }
}

From source file:com.pc.dailymile.DailyMileClient.java

public Long addNoteWithImage(String note, File imageFile) throws Exception {
    HttpPost request = new HttpPost(DailyMileUtil.ENTRIES_URL);
    HttpResponse response = null;/*from  w  w  w. j  av a 2 s.c o m*/
    try {
        MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        mpEntity.addPart("media[data]", new FileBody(imageFile, "image/jpeg"));
        mpEntity.addPart("media[type]", new StringBody("image"));
        mpEntity.addPart("message", new StringBody(note));
        mpEntity.addPart("[share_on_services][facebook]", new StringBody("false"));
        mpEntity.addPart("[share_on_services][twitter]", new StringBody("false"));
        mpEntity.addPart("oauth_token", new StringBody(oauthToken));

        request.setEntity(mpEntity);
        // send the request
        response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 401) {
            throw new RuntimeException(
                    "unable to execute POST - url: " + DailyMileUtil.ENTRIES_URL + " body: " + note);
        }

        if (statusCode == 201) {
            Header loc = response.getFirstHeader("Location");
            if (loc != null) {
                String locS = loc.getValue();
                if (!StringUtils.isBlank(locS) && locS.matches(".*/[0-9]+$")) {
                    try {
                        return NumberUtils.createLong(locS.substring(locS.lastIndexOf("/") + 1));
                    } catch (NumberFormatException e) {
                        return null;
                    }
                }
            }
        }

        return null;
    } finally {
        try {
            if (response != null) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    entity.consumeContent();
                }
            }
            //EntityUtils.consume(response.getEntity());
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:cc.mincai.android.desecret.storage.dropbox.DropboxClient.java

/**
 * Put a file in the user's Dropbox./*from  w  ww. j av a2s . c  o m*/
 */
@SuppressWarnings("unchecked")
public HttpResponse putFile(String root, String to_path, File file_obj) throws DropboxException {
    String path = "/files/" + root + to_path;

    HttpClient client = getClient();

    try {
        String target = buildFullURL(secureProtocol, content_host, this.port,
                buildURL(path, API_VERSION, null));
        HttpPost req = new HttpPost(target);
        // this has to be done this way because of how oauth signs params
        // first we add a "fake" param of file=path of *uploaded* file
        // THEN we sign that.
        List nvps = new ArrayList();
        nvps.add(new BasicNameValuePair("file", file_obj.getName()));
        req.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        auth.sign(req);

        // now we can add the real file multipart and we're good
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        FileBody bin = new FileBody(file_obj);
        entity.addPart("file", bin);
        // this resets it to the new entity with the real file
        req.setEntity(entity);

        HttpResponse resp = client.execute(req);

        resp.getEntity().consumeContent();
        return resp;
    } catch (Exception e) {
        throw new DropboxException(e);
    }
}