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.marietjedroid.connect.MarietjeMessenger.java

/**
 * Sends a stream//from w ww . j  a  va  2  s .c  o m
 * 
 * FIXME probably massively broken
 * 
 * @param token
 * @param stream
 * @param blocking
 */
public void sendStream(String token, ContentBody stream, boolean blocking) {
    if (!this.token.equals(token))
        throw new IllegalArgumentException("Wrong token!");

    MultipartEntity multipartStream = new MultipartEntity();
    multipartStream.addPart("stream", stream);

    final HttpPost post = new HttpPost(String.format("http://%s:%s%s", host, port, path));
    // FIXME sowieso stuk
    post.setEntity(multipartStream);

    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                httpClient.execute(post);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    t.start();

    if (blocking) {
        try {
            t.join();
        } catch (InterruptedException e) {

        }
    }

}

From source file:pl.psnc.synat.wrdz.zmkd.plan.MigrationPlanProcessorBean.java

/**
 * Creates a new object in ZMD.//from  w w  w  . ja v a 2 s  .  co m
 * 
 * @param client
 *            http client instance
 * @param files
 *            map of the new object's files; keys contain the file names/paths inside the new object's structure
 * @param fileSequence
 *            map of the new object's file sequence values; keys contain the file names/paths inside the new
 *            object's structure
 * @param originIdentifier
 *            identifier of the object the new object was migrated from
 * @param originType
 *            the type of migration performed
 * @return creation request identifier
 * @throws IOException
 *             if object upload fails
 */
private String saveObject(HttpClient client, Map<String, File> files, Map<String, Integer> fileSequence,
        String originIdentifier, MigrationType originType) throws IOException {

    DateFormat format = new SimpleDateFormat(ORIGIN_DATE_FORMAT);

    HttpPost post = new HttpPost(zmkdConfiguration.getZmdObjectUrl());
    MultipartEntity entity = new MultipartEntity();

    try {

        entity.addPart(ORIGIN_ID, new StringBody(originIdentifier, ENCODING));
        entity.addPart(ORIGIN_TYPE, new StringBody(originType.name(), ENCODING));
        entity.addPart(ORIGIN_DATE, new StringBody(format.format(new Date()), ENCODING));

        int i = 0;
        for (Entry<String, File> dataFile : files.entrySet()) {
            FileBody file = new FileBody(dataFile.getValue());
            StringBody path = new StringBody(dataFile.getKey(), ENCODING);

            entity.addPart(String.format(FILE_SRC, i), file);
            entity.addPart(String.format(FILE_DEST, i), path);

            if (fileSequence.containsKey(dataFile.getKey())) {
                StringBody seq = new StringBody(fileSequence.get(dataFile.getKey()).toString(), ENCODING);
                entity.addPart(String.format(FILE_SEQ, i), seq);
            }

            i++;
        }
    } catch (UnsupportedEncodingException e) {
        throw new WrdzRuntimeException("The encoding " + ENCODING + " is not supported");
    }

    post.setEntity(entity);

    HttpResponse response = client.execute(post);
    EntityUtils.consumeQuietly(response.getEntity());
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) {
        String location = response.getFirstHeader("location").getValue();
        return location.substring(location.lastIndexOf('/') + 1);
    } else {
        throw new IOException("Unexpected response: " + response.getStatusLine());
    }
}

From source file:alien4cloud.paas.cloudify2.rest.external.RestClientExecutor.java

/**
 *
 * @param relativeUrl/* w  ww  .  j  ava2 s.  co  m*/
 *            The URL to post to.
 * @param fileToPost
 *            The file to post.
 * @param partName
 *            The name of the request parameter (the posted file) to bind to.
 * @param responseTypeReference
 *            The type reference of the response.
 * @param <T> The type of the response.
 * @return The response object from the REST server.
 * @throws RestClientException
 *             Reporting failure to post the file.
 */
public <T> T postFile(final String relativeUrl, final File fileToPost, final String partName,
        final TypeReference<Response<T>> responseTypeReference) throws RestClientException {
    final MultipartEntity multipartEntity = new MultipartEntity();
    final FileBody fileBody = new FileBody(fileToPost);
    multipartEntity.addPart(partName, fileBody);
    if (logger.isLoggable(Level.FINE)) {
        logger.log(Level.FINE,
                "executing post request to " + relativeUrl + ", tring to post file " + fileToPost.getName());
    }
    return post(relativeUrl, responseTypeReference, multipartEntity);
}

From source file:org.obiba.opal.rest.client.magma.OpalJavaClient.java

public HttpResponse post(URI uri, File file) throws IOException {
    HttpPost post = new HttpPost(uri);
    MultipartEntity me = new MultipartEntity();
    me.addPart("fileToUpload", new FileBody(file));
    post.setEntity(me);//from  w  w  w .j  ava  2s.com
    return execute(post);
}

From source file:com.ibuildapp.romanblack.TableReservationPlugin.TableReservationEMailSignUpActivity.java

/**
 * Validate input data and signs up new user on iBuildApp.
 *///w  ww  .  jav a2s  . co  m
private void registration() {
    if (signUpActive) {
        handler.sendEmptyMessage(SHOW_PROGRESS_DIALOG);

        new Thread(new Runnable() {
            public void run() {

                HttpParams params = new BasicHttpParams();
                params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
                HttpClient httpClient = new DefaultHttpClient(params);

                try {
                    HttpPost httpPost = new HttpPost(TableReservationHTTP.SIGNUP_URL);

                    String firstNameString = firstNameEditText.getText().toString();
                    String lastNameString = lastNameEditText.getText().toString();
                    String emailString = emailEditText.getText().toString();
                    String passwordString = passwordEditText.getText().toString();
                    String rePasswordString = rePasswordEditText.getText().toString();

                    MultipartEntity multipartEntity = new MultipartEntity();
                    multipartEntity.addPart("firstname",
                            new StringBody(firstNameString, Charset.forName("UTF-8")));
                    multipartEntity.addPart("lastname",
                            new StringBody(lastNameString, Charset.forName("UTF-8")));
                    multipartEntity.addPart("email", new StringBody(emailString, Charset.forName("UTF-8")));
                    multipartEntity.addPart("password",
                            new StringBody(passwordString, Charset.forName("UTF-8")));
                    multipartEntity.addPart("password_confirm",
                            new StringBody(rePasswordString, Charset.forName("UTF-8")));

                    // add security part
                    multipartEntity.addPart("app_id", new StringBody(Statics.appId, Charset.forName("UTF-8")));
                    multipartEntity.addPart("token",
                            new StringBody(Statics.appToken, Charset.forName("UTF-8")));

                    httpPost.setEntity(multipartEntity);

                    String resp = httpClient.execute(httpPost, new BasicResponseHandler());

                    fwUser = JSONParser.parseLoginRequestString(resp);

                    if (fwUser == null) {
                        handler.sendEmptyMessage(EMEIL_IN_USE);
                        handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG);
                        return;
                    }

                    handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG);

                    handler.sendEmptyMessage(CLOSE_ACTIVITY_OK);

                } catch (Exception e) {
                    handler.sendEmptyMessage(CLOSE_ACTIVITY_BAD);
                }

            }
        }).start();
    } else {
        if (firstNameEditText.getText().toString().length() == 0
                || lastNameEditText.getText().toString().length() == 0
                || emailEditText.getText().toString().length() == 0
                || passwordEditText.getText().toString().length() == 0
                || rePasswordEditText.getText().toString().length() == 0) {
            Toast.makeText(this, R.string.alert_registration_fillin_fields, Toast.LENGTH_LONG).show();
            return;
        }

        if (firstNameEditText.getText().toString().equals(lastNameEditText.getText().toString())) {
            Toast.makeText(this, R.string.alert_registration_spam, Toast.LENGTH_LONG).show();
            return;
        }

        if (firstNameEditText.getText().toString().length() <= 2
                || lastNameEditText.getText().toString().length() <= 2) {
            Toast.makeText(this, R.string.alert_registration_two_symbols_name, Toast.LENGTH_LONG).show();
            return;
        }

        String regExpn = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
                + "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?" + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
                + "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?" + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
                + "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";

        Pattern pattern = Pattern.compile(regExpn, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(emailEditText.getText().toString());

        if (matcher.matches()) {
        } else {
            Toast.makeText(this, R.string.alert_registration_correct_email, Toast.LENGTH_LONG).show();
            return;
        }

        if (passwordEditText.getText().toString().length() < 4) {
            Toast.makeText(this, R.string.alert_registration_two_symbols_password, Toast.LENGTH_LONG).show();
            return;
        }

        if (!passwordEditText.getText().toString().equals(rePasswordEditText.getText().toString())) {
            Toast.makeText(this, "Passwords don't match.", Toast.LENGTH_LONG).show();
            return;
        }
    }
}

From source file:org.rhq.modules.plugins.wildfly10.ASUploadConnection.java

/**
 * Triggers the real upload to the AS7 instance. At this point the caller should have written 
 * the content in the {@link OutputStream} given by {@link #getOutputStream()}.
 * //from   w w  w  . j  ava 2 s. c  o  m
 * @return a {@link JsonNode} instance read from the upload response body or null if something went wrong.
 */
public JsonNode finishUpload() {
    if (filename == null) {
        // At this point the fileName should have been set whether at instanciation or in #getOutputStream(String)
        throw new IllegalStateException("Upload fileName is null");
    }

    closeQuietly(cacheOutputStream);

    SchemeRegistry schemeRegistry = new SchemeRegistryBuilder(asConnectionParams).buildSchemeRegistry();
    ClientConnectionManager httpConnectionManager = new BasicClientConnectionManager(schemeRegistry);
    DefaultHttpClient httpClient = new DefaultHttpClient(httpConnectionManager);
    HttpParams httpParams = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, SOCKET_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, timeout);

    if (credentials != null && !asConnectionParams.isClientcertAuthentication()) {
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(asConnectionParams.getHost(), asConnectionParams.getPort()), credentials);

        // If credentials were provided, we will first send a GET request to trigger the authentication challenge
        // This allows to send the potentially big file only once to the server
        // The typical resulting http exchange would be:
        //
        // GET without auth <- 401 (start auth challenge : the server will name the realm and the scheme)
        // GET with auth <- 200
        // POST big file
        //
        // Note this only works because we use SimpleHttpConnectionManager which maintains only one HttpConnection
        //
        // A better way to avoid uploading a big file twice would be to use the header "Expect: Continue"
        // Unfortunately AS7 replies "100 Continue" even if authentication headers are not present yet
        //
        // There is no need to trigger digest authentication when client certification authentication is used

        HttpGet triggerAuthRequest = new HttpGet(triggerAuthUri);
        try {
            // Send GET request in order to trigger authentication
            // We don't check response code because we're not already uploading the file
            httpClient.execute(triggerAuthRequest);
        } catch (Exception ignore) {
            // We don't stop trying upload if triggerAuthRequest raises exception
            // See comment above
        } finally {
            triggerAuthRequest.abort();
        }
    }

    String uploadURL = (asConnectionParams.isSecure() ? ASConnection.HTTPS_SCHEME : ASConnection.HTTP_SCHEME)
            + "://" + asConnectionParams.getHost() + ":" + asConnectionParams.getPort() + UPLOAD_URI;
    HttpPost uploadRequest = new HttpPost(uploadUri);
    try {

        // Now upload file with multipart POST request
        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart(filename, new FileBody(cacheFile));
        uploadRequest.setEntity(multipartEntity);
        HttpResponse uploadResponse = httpClient.execute(uploadRequest);
        if (uploadResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            logUploadDoesNotEndWithHttpOkStatus(uploadResponse);
            return null;
        }

        ObjectMapper objectMapper = new ObjectMapper();
        InputStream responseBodyAsStream = uploadResponse.getEntity().getContent();
        if (responseBodyAsStream == null) {
            LOG.warn("POST request has no response body");
            return objectMapper.readTree(EMPTY_JSON_TREE);
        }
        return objectMapper.readTree(responseBodyAsStream);

    } catch (Exception e) {
        LOG.error(e);
        return null;
    } finally {
        // Release httpclient resources
        uploadRequest.abort();
        httpConnectionManager.shutdown();
        // Delete cache file
        deleteCacheFile();
    }
}

From source file:com.android.flickrbot.FlickrClient.java

/**
 * Upload a photo to Flickr using the current user credentials.
 * //from www  . ja v  a 2 s .co m
 * @param title Photo title
 * @param description Photo description
 * @param tags Tags to assign to photo
 * @param image JPEG object representing the photo
 */
public void sendPhoto(String title, String description, String tags, InputStream image) throws Exception {
    // TODO: Verify that we are authorized first.

    // Build a representation of the parameter list, and use it to sign the request.
    parameterList params = this.new parameterList();
    params.addParameter("api_key", KEY);
    params.addParameter("auth_token", m_database.getConfigValue(AUTH_TOKEN_NAME));

    // Add all of the extra parameters that are passed along with the image.
    if (title.length() > 0) {
        params.addParameter("title", title);
    }

    if (description.length() > 0) {
        params.addParameter("description", description);
    }

    if (tags.length() > 0) {
        params.addParameter("tags", tags);
    }

    // Build a multipart HTTP request to post to Flickr

    // Add the text parameters
    MultipartEntity multipart = params.getMultipartEntity();

    // then the photo data
    multipart.addPart("photo", new InputStreamBody(image, "photo"));

    // Build the rest of the players
    HttpClient client = new DefaultHttpClient(); // HttpClient makes requests
    HttpPost postrequest = new HttpPost(UPLOAD_URL); // HttpPost is the type of request we are making
    postrequest.setEntity(multipart);
    HttpResponse response; // HttpResponse holds the return data from HttpPost 

    // TODO: Is this necessary?
    if (postrequest == null) {
        // Building the post request has failed
        throw new Exception("postrequest could not be built");
    }

    // Post the photo.  This will throw an exception if the connection fails.
    response = client.execute(postrequest);

    System.out.println("POST response code: " + response.getStatusLine().getReasonPhrase());
    HttpEntity resp = response.getEntity();

    if (resp == null) {
        throw new Exception("Response entity is empty.");
    }

    byte[] b = new byte[999];
    resp.getContent().read(b);
    System.out.println("Response: " + new String(b));

}

From source file:com.atlassian.jira.rest.client.internal.async.AsynchronousIssueRestClient.java

@Override
public Promise<Void> addAttachments(final URI attachmentsUri, final File... files) {
    final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
            Charset.defaultCharset());
    for (final File file : files) {
        entity.addPart(FILE_BODY_TYPE, new FileBody(file));
    }//w w w .j  av a2 s  .  c  o  m
    return postAttachments(attachmentsUri, entity);
}

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

  /**
 * Uploads the image to Google Cloud Storage.
 *//*from www. java 2s.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;
}