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.onaio.steps.helper.UploadFileTask.java

@Override
protected Boolean doInBackground(File... files) {
    if (!TextUtils.isEmpty(KeyValueStoreFactory.instance(activity).getString(ENDPOINT_URL))) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(KeyValueStoreFactory.instance(activity).getString(ENDPOINT_URL));
        try {/*w  w  w.j a v a  2  s  .  co m*/
            MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                    Charset.forName("UTF-8"));
            multipartEntity.addPart("file", new FileBody(files[0]));
            httpPost.setEntity(multipartEntity);
            httpClient.execute(httpPost);
            new CustomNotification().notify(activity, R.string.export_complete,
                    R.string.export_complete_message);
            return true;
        } catch (IOException e) {
            new Logger().log(e, "Export failed.");
            new CustomNotification().notify(activity, R.string.error_title, R.string.export_failed);
        }
    } else {
        new CustomNotification().notify(activity, R.string.error_title, R.string.export_failed);
    }

    return false;
}

From source file:org.semantictools.jsonld.impl.AppspotContextPublisher.java

@Override
public void publish(LdAsset asset) throws LdPublishException {

    String uri = asset.getURI();//  ww w.  ja  va 2s .  co m

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(SERVLET_URL);
    post.setHeader("CONTENT-TYPE", "multipart/form-data; boundary=xxxBOUNDARYxxx");
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "xxxBOUNDARYxxx",
            Charset.forName("UTF-8"));

    try {

        String content = asset.loadContent();

        entity.addPart(URI, new StringBody(uri));
        entity.addPart(FILE_UPLOAD, new StringBody(content));
        post.setEntity(entity);

        logger.debug("uploading... " + uri);

        HttpResponse response = client.execute(post);
        int status = response.getStatusLine().getStatusCode();

        client.getConnectionManager().shutdown();
        if (status != HttpURLConnection.HTTP_OK) {
            throw new LdPublishException(uri, null);
        }

    } catch (Exception e) {
        throw new LdPublishException(uri, e);
    }

}

From source file:com.easycode.common.HttpUtil.java

public static byte[] httpPost(String url, List<FormItem> blist) throws Exception {
    byte[] ret = null;
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
            Charset.forName("UTF-8"));
    if (blist != null) {
        for (FormItem f : blist) {
            reqEntity.addPart(f.getName(), f.getCtx());
        }/*w w  w.j a  va 2 s. c om*/
    }
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);

    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
        InputStream tis = resEntity.getContent();

        java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = tis.read(bytes)) > 0) {
            out.write(bytes, 0, len);
        }
        ret = out.toByteArray();
    }
    EntityUtils.consume(resEntity);
    try {
        httpclient.getConnectionManager().shutdown();
    } catch (Exception ignore) {
    }
    return ret;
}

From source file:fedroot.dacs.http.DacsPostRequest.java

/**
 * the following, which includes parameters in the multipart entity is not grokked
 * by DACS multipart parsing//  ww w.ja  v a 2s.  c o m
 * @param webServiceRequest
 * @return
 */
private HttpPost multipartBrokenPost(WebServiceRequest webServiceRequest) {
    try {
        HttpPost multipartPost = new HttpPost(webServiceRequest.getBaseURI());
        //            multipartPost.setHeader("Content-Type", webServiceRequest.getEnclosureType());
        multipartPost.setHeader("Content-Transfer-Encoding", "7bit");
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                "----HttpClientBoundarynSbUMwsZpJVNlFYK", Charset.forName("US-ASCII"));

        for (NameValuePair nameValuePair : webServiceRequest.getNameValuePairs()) {
            multipartEntity.addPart(nameValuePair.getName(),
                    new StringBody(new String(nameValuePair.getValue().getBytes(), Charset.forName("US-ASCII")),
                            Charset.forName("US-ASCII")));
        }
        for (NameFilePair nameFilePair : webServiceRequest.getNameFilePairs()) {
            multipartEntity.addPart(nameFilePair.getName(), nameFilePair.getFileBody());
        }
        multipartPost.setEntity(multipartEntity);
        return multipartPost;
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(DacsPostRequest.class.getName()).log(Level.SEVERE, null, ex);
        throw new RuntimeException("Invalid DacsWebServiceRequest parameters " + ex.getMessage());
    }
}

From source file:outfox.ynote.open.client.YNoteHttpUtils.java

/**
 * Do a http post with the multipart content type. This method is usually
 * used to upload the large size content, such as uploading a file.
 *
 * @param url/*from w w w  .j a  va2s.c om*/
 * @param formParams
 * @param accessor
 * @return
 * @throws IOException
 * @throws YNoteException
 */
public static HttpResponse doPostByMultipart(String url, Map<String, Object> formParams, OAuthAccessor accessor)
        throws IOException, YNoteException {
    HttpPost post = new HttpPost(url);
    // for multipart encoded post, only sign with the oauth parameters
    // do not sign the our form parameters
    Header oauthHeader = getAuthorizationHeader(url, OAuthMessage.POST, null, accessor);
    if (formParams != null) {
        // encode our ynote parameters
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                Charset.forName("UTF-8"));
        for (Entry<String, Object> parameter : formParams.entrySet()) {
            if (parameter.getValue() instanceof File) {
                // deal with file particular
                entity.addPart(parameter.getKey(), new FileBody((File) parameter.getValue()));
            } else if (parameter.getValue() != null) {
                entity.addPart(parameter.getKey(), new StringBody(parameter.getValue().toString(),
                        Charset.forName(YNoteConstants.ENCODING)));
            }
        }
        post.setEntity(entity);
    }
    post.addHeader(oauthHeader);
    HttpResponse response = client.execute(post);
    if ((response.getStatusLine().getStatusCode() / 100) != 2) {
        YNoteException e = wrapYNoteException(response);
        throw e;
    }
    return response;
}

From source file:io.undertow.servlet.test.multipart.MultiPartTestCase.java

@Test
public void testMultiPartRequest() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {//  ww w.ja va 2s  .  c  o  m
        String uri = DefaultServer.getDefaultServerURL() + "/servletContext/1";
        HttpPost post = new HttpPost(uri);

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                StandardCharsets.UTF_8);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file",
                new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("PARAMS:\n" + "name: formValue\n" + "filename: null\n" + "content-type: null\n"
                + "Content-Disposition: form-data; name=\"formValue\"\n" + "size: 7\n" + "content: myValue\n"
                + "name: file\n" + "filename: uploadfile.txt\n" + "content-type: application/octet-stream\n"
                + "Content-Disposition: form-data; name=\"file\"; filename=\"uploadfile.txt\"\n"
                + "Content-Type: application/octet-stream\n" + "size: 13\n" + "content: file contents\n",
                response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.siahmsoft.soundroid.sdk7.services.UploadService.java

public void uploadTrack(Bundle bundle) {

    Track track = TracksStore.Track.fromBundle(bundle);
    //SystemClock.sleep(1500);

    if (track.getmIdTrack() == 0) {

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                Charset.forName(HTTP.UTF_8));

        try {/*from   w ww  . jav a 2s  .co  m*/

            if (track.getmTrackPath() != null && !"".equals(track.getmTrackPath())) {
                ContentBody asset_Data = new FileBody(new File(track.getmTrackPath()));
                entity.addPart("track[asset_data]", asset_Data);
            }

            if (track.getmArtworkPath() != null && !"".equals(track.getmArtworkPath())) {
                ContentBody artworkData = new FileBody(new File(track.getmArtworkPath()));
                entity.addPart("track[artwork_data]", artworkData);
            }

            if (track.getmTitle() != null && !"".equals(track.getmTitle())) {
                entity.addPart("track[title]", new StringBody(track.getmTitle()));
            }

            if (track.getmDescription() != null && !"".equals(track.getmDescription())) {
                entity.addPart("track[description]", new StringBody(track.getmDescription()));
            }

            if (track.getmDownloadable() != null && !"".equals(track.getmDownloadable())) {
                entity.addPart("track[downloadable]", new StringBody(track.getmDownloadable()));
            }

            if (track.getmSharing() != null && !"".equals(track.getmSharing())) {
                entity.addPart("track[sharing]", new StringBody(track.getmSharing()));
            }

            if (!"".equals(track.getmBpm())) {
                entity.addPart("track[bpm]", new StringBody(String.valueOf(track.getmBpm())));
            }

            if (track.getmTagList() != null && !"".equals(track.getmTagList())) {
                entity.addPart("track[tag_list]", new StringBody(track.getmTagList()));
            }

            if (track.getmGenre() != null && !"".equals(track.getmGenre())) {
                entity.addPart("track[genre]", new StringBody(track.getmGenre()));
            }

            if (track.getmLicense() != null && !"".equals(track.getmLicense())) {
                entity.addPart("track[license]", new StringBody(track.getmLicense()));
            }

            if (track.getmLabelName() != null && !"".equals(track.getmLabelName())) {
                entity.addPart("track[label_name]", new StringBody(track.getmLabelName()));
            }

            if (track.getmTrackType() != null && !"".equals(track.getmTrackType())) {
                entity.addPart("track[track_type]", new StringBody(track.getmTrackType()));
            }

            HttpPost filePost = new HttpPost("http://api.soundcloud.com/tracks");
            Soundroid.getSc().signRequest(filePost);
            filePost.setEntity(entity);

            try {
                //SystemClock.sleep(1000);
                showNotification("Uploading track " + track.getmTitle());
                final HttpResponse response = sClient.execute(filePost);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
                    showNotification("Track " + track.getmTitle() + " uploaded");
                    sClient.getConnectionManager().closeExpiredConnections();
                    totalUploads--;
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        } catch (Exception e) {

        }
    } else {//Edicin de la cancin

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                Charset.forName(HTTP.UTF_8));
        try {

            if (track.getmTrackPath() != null && !"".equals(track.getmTrackPath())) {
                ContentBody asset_Data = new FileBody(new File(track.getmTrackPath()));
                entity.addPart("track[asset_data]", asset_Data);
            }

            if (track.getmArtworkPath() != null && !"".equals(track.getmArtworkPath())) {
                ContentBody artworkData = new FileBody(new File(track.getmArtworkPath()));
                entity.addPart("track[artwork_data]", artworkData);
            }

            if (track.getmTitle() != null) {
                entity.addPart("track[title]", new StringBody(track.getmTitle()));
            }

            if (track.getmDescription() != null) {
                entity.addPart("track[description]", new StringBody(track.getmDescription()));
            }

            if (track.getmDownloadable() != null) {
                entity.addPart("track[downloadable]", new StringBody(track.getmDownloadable()));
            }

            if (track.getmSharing() != null) {
                entity.addPart("track[sharing]", new StringBody(track.getmSharing()));
            }

            entity.addPart("track[bpm]", new StringBody(String.valueOf(track.getmBpm())));

            if (track.getmTagList() != null) {
                entity.addPart("track[tag_list]", new StringBody(track.getmTagList()));
            }

            if (track.getmGenre() != null) {
                entity.addPart("track[genre]", new StringBody(track.getmGenre()));
            }

            if (track.getmLicense() != null) {
                entity.addPart("track[license]", new StringBody(track.getmLicense()));
            }

            if (track.getmLabelName() != null) {
                entity.addPart("track[label_name]", new StringBody(track.getmLabelName()));
            }

            if (track.getmTrackType() != null) {
                entity.addPart("track[track_type]", new StringBody(track.getmTrackType()));
            }

            HttpPut filePut = new HttpPut("http://api.soundcloud.com/tracks/" + track.getmIdTrack() + ".json");
            Soundroid.getSc().signRequest(filePut);

            filePut.setEntity(entity);

            try {
                //SystemClock.sleep(1000);
                showNotification("Uploading track " + track.getmTitle());
                final HttpResponse response = sClient.execute(filePut);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
                    showNotification("Track " + track.getmTitle() + " edited");
                    sClient.getConnectionManager().closeExpiredConnections();
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        } catch (Exception e) {

        }
    }
}

From source file:net.idea.opentox.cli.dataset.DatasetClient.java

@Override
protected HttpEntity createPOSTEntity(Dataset dataset, List<POLICY_RULE> accessRights)
        throws InvalidInputException, Exception {
    if (dataset.getInputData() == null || dataset.getInputData().getInputFile() == null)
        throw new InvalidInputException("File to import not defined!");
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, utf8);

    entity.addPart(_WEBFORM.title.name(), new StringBody(dataset.getMetadata().getTitle(), utf8));
    entity.addPart(_WEBFORM.seeAlso.name(), new StringBody(dataset.getMetadata().getSeeAlso(), utf8));
    entity.addPart(_WEBFORM.license.name(),
            new StringBody(dataset.getMetadata().getRights() == null ? ""
                    : (dataset.getMetadata().getRights().getURI() == null ? ""
                            : dataset.getMetadata().getRights().getURI()),
                    utf8));//w  ww.ja  v a 2s . c  o m
    entity.addPart(_WEBFORM.match.name(),
            new StringBody(dataset.getInputData().getImportMatchMode().name(), utf8));
    entity.addPart(_WEBFORM.file.name(), new FileBody(dataset.getInputData().getInputFile()));

    return entity;
}

From source file:org.opendatakit.aggregate.externalservice.OhmageJsonServer.java

/**
 * Uploads a set of submissions to the ohmage system.
 *
 * @throws IOException//from  www .  j  av a2  s  .c om
 * @throws ClientProtocolException
 * @throws ODKExternalServiceException
 * @throws URISyntaxException
 */
public void uploadSurveys(List<OhmageJsonTypes.Survey> surveys, Map<UUID, ByteArrayBody> photos,
        CallingContext cc)
        throws ClientProtocolException, IOException, ODKExternalServiceException, URISyntaxException {

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT, null, UTF_CHARSET);
    // emit the configured publisher parameters if the values are non-empty...
    String value;
    value = getOhmageCampaignUrn();
    if (value != null && value.length() != 0) {
        StringBody campaignUrn = new StringBody(getOhmageCampaignUrn(), UTF_CHARSET);
        reqEntity.addPart("campaign_urn", campaignUrn);
    }
    value = getOhmageCampaignCreationTimestamp();
    if (value != null && value.length() != 0) {
        StringBody campaignCreationTimestamp = new StringBody(getOhmageCampaignCreationTimestamp(),
                UTF_CHARSET);
        reqEntity.addPart("campaign_creation_timestamp", campaignCreationTimestamp);
    }
    value = getOhmageUsername();
    if (value != null && value.length() != 0) {
        StringBody user = new StringBody(getOhmageUsername(), UTF_CHARSET);
        reqEntity.addPart("user", user);
    }
    value = getOhmageHashedPassword();
    if (value != null && value.length() != 0) {
        StringBody hashedPassword = new StringBody(getOhmageHashedPassword(), UTF_CHARSET);
        reqEntity.addPart("passowrd", hashedPassword);
    }
    // emit the client identity and the json representation of the survey...
    StringBody clientParam = new StringBody(cc.getServerURL());
    reqEntity.addPart("client", clientParam);
    StringBody surveyData = new StringBody(gson.toJson(surveys));
    reqEntity.addPart("survey", surveyData);

    // emit the file streams for all the media attachments
    for (Entry<UUID, ByteArrayBody> entry : photos.entrySet()) {
        reqEntity.addPart(entry.getKey().toString(), entry.getValue());
    }

    HttpResponse response = super.sendHttpRequest(POST, getServerUrl(), reqEntity, null, cc);
    String responseString = WebUtils.readResponse(response);
    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
        throw new ODKExternalServiceCredentialsException(
                "failure from server: " + statusCode + " response: " + responseString);
    } else if (statusCode >= 300) {
        throw new ODKExternalServiceException(
                "failure from server: " + statusCode + " response: " + responseString);
    }
}

From source file:org.semantictools.web.upload.AppspotUploadClient.java

public void upload(String contentType, String path, File file) throws IOException {

    if (file.getName().equals(CHECKSUM_PROPERTIES)) {
        return;//from   w ww .j a  v a  2s . c  om
    }

    if (!path.startsWith("/")) {
        path = "/" + path;
    }

    // Do not upload if we can confirm that we previously uploaded
    // the same content.

    String checksumKey = path.concat(".sha1");
    String checksumValue = null;
    try {
        checksumValue = Checksum.sha1(file);
        String prior = checksumProperties.getProperty(checksumKey);
        if (checksumValue.equals(prior)) {
            return;
        }

    } catch (NoSuchAlgorithmException e) {
        // Ignore.
    }

    logger.debug("uploading... " + path);

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(servletURL);
    post.setHeader("CONTENT-TYPE", "multipart/form-data; boundary=xxxBOUNDARYxxx");
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "xxxBOUNDARYxxx",
            Charset.forName("UTF-8"));

    FileBody body = new FileBody(file, contentType);

    entity.addPart(CONTENT_TYPE, new StringBody(contentType));
    entity.addPart(PATH, new StringBody(path));
    if (version != null) {
        entity.addPart(VERSION, new StringBody(version));
    }
    entity.addPart(FILE_UPLOAD, body);

    post.setEntity(entity);

    String response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");

    client.getConnectionManager().shutdown();

    if (checksumValue != null) {
        checksumProperties.put(checksumKey, checksumValue);
    }

}