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:fm.smart.r1.ItemActivity.java

public AddImageResult addImage(File file, String media_entity, String author, String author_url,
        String attribution_license_id, String sentence_id, String item_id, String list_id) {
    String http_response = "";
    int status_code = 0;
    HttpClient client = null;// www.j  a v  a2  s .  com
    try {
        client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://api.smart.fm/lists/" + list_id + "/items/" + item_id
                + "/sentences/" + sentence_id + "/images");
        // HttpPost post = new HttpPost("http://api.smart.fm/sentences/" +
        // sentence_id
        // + "/images");

        String auth = LoginActivity.username(this) + ":" + LoginActivity.password(this);
        byte[] bytes = auth.getBytes();
        post.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64(bytes)));

        // httppost.setHeader("Content-Type",
        // "application/x-www-form-urlencoded");

        post.setHeader("Host", "api.smart.fm");

        FileBody bin = new FileBody(file, "image/jpeg");
        StringBody media_entity_part = new StringBody(media_entity);
        StringBody author_part = new StringBody(author);
        StringBody author_url_part = new StringBody(author_url);
        StringBody attribution_license_id_part = new StringBody(attribution_license_id);
        StringBody sentence_id_part = new StringBody(sentence_id);
        StringBody api_key_part = new StringBody(Main.API_KEY);
        StringBody item_id_part = new StringBody(item_id);
        StringBody list_id_part = new StringBody(list_id);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("image[file]", bin);
        reqEntity.addPart("media_entity", media_entity_part);
        reqEntity.addPart("author", author_part);
        reqEntity.addPart("author_url", author_url_part);
        reqEntity.addPart("attribution_license_id", attribution_license_id_part);
        reqEntity.addPart("sentence_id", sentence_id_part);
        reqEntity.addPart("api_key", api_key_part);
        reqEntity.addPart("item_id", item_id_part);
        reqEntity.addPart("list_id", list_id_part);

        post.setEntity(reqEntity);

        Header[] array = post.getAllHeaders();
        for (int i = 0; i < array.length; i++) {
            Log.d("DEBUG", array[i].toString());
        }

        Log.d("AddImage", "executing request " + post.getRequestLine());
        HttpResponse response = client.execute(post);
        HttpEntity resEntity = response.getEntity();
        status_code = response.getStatusLine().getStatusCode();

        Log.d("AddImage", "----------------------------------------");
        Log.d("AddImage", response.getStatusLine().toString());
        array = response.getAllHeaders();
        for (int i = 0; i < array.length; i++) {
            Log.d("AddImage", array[i].toString());
        }
        if (resEntity != null) {
            Log.d("AddImage", "Response content length: " + resEntity.getContentLength());
            Log.d("AddImage", "Chunked?: " + resEntity.isChunked());
        }
        long length = response.getEntity().getContentLength();
        byte[] response_bytes = new byte[(int) length];
        response.getEntity().getContent().read(response_bytes);
        Log.d("AddImage", new String(response_bytes));
        http_response = new String(response_bytes);
        if (resEntity != null) {
            resEntity.consumeContent();
        }

        // HttpEntity entity = response1.getEntity();
    } catch (IOException e) {
        /* Reset to Default image on any error. */
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return new AddImageResult(status_code, http_response);
}

From source file:org.wso2.am.integration.tests.other.APIImportExportTestCase.java

/**
 * Upload a file to the given URL// www  .java2s .  co m
 *
 * @param importUrl URL to be file upload
 * @param fileName  Name of the file to be upload
 * @throws IOException throws if connection issues occurred
 */
private void importAPI(String importUrl, File fileName, String user, char[] pass) throws IOException {
    //open import API url connection and deploy the exported API
    URL url = new URL(importUrl);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");

    FileBody fileBody = new FileBody(fileName);
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
    multipartEntity.addPart("file", fileBody);

    connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
    connection.setRequestProperty(APIMIntegrationConstants.AUTHORIZATION_HEADER,
            "Basic " + encodeCredentials(user, pass));
    OutputStream out = connection.getOutputStream();
    try {
        multipartEntity.writeTo(out);
    } finally {
        out.close();
    }
    int status = connection.getResponseCode();
    BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String temp;
    StringBuilder response = new StringBuilder();
    while ((temp = read.readLine()) != null) {
        response.append(temp);
    }
    Assert.assertEquals(status, HttpStatus.SC_CREATED, "Response code is not as expected : " + response);
}

From source file:de.geomobile.joined.api.service.JOWebService.java

/**
 * Activate or deactivate user//  w w w . j  av a2 s.  c o  m
 * 
 * @param userId
 *            The users id.
 * 
 * @param secureToken
 *            The users secureToken.
 * @param active
 *            active or deactive
 * @throws JOFriendFinderUnexpectedException
 * @throws JOFriendFinderServerException
 * @throws JOFriendFinderHTTPException
 */
public void activateUser(String userId, String secureToken, boolean active)
        throws JOFriendFinderUnexpectedException, JOFriendFinderServerException, JOFriendFinderHTTPException {
    try {
        HttpClient httpClient = getNewHttpClient();
        HttpPut httpput = new HttpPut(getJoinedServerUrl() + JOConfig.FF_FRIENDS + "/" + userId);
        httpput.addHeader(getAuthenticationHeader(userId, secureToken));
        MultipartEntity entity = new MultipartEntity();
        entity.addPart(JOConfig.IS_ACTIVE,
                new StringBody(String.valueOf(active), Charset.forName(JOConfig.UTF_8)));

        httpput.setEntity(entity);
        HttpResponse httpResponse = httpClient.execute(httpput);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            throw new JOFriendFinderServerException();
        } else if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {
            throw new JOFriendFinderUnexpectedException(
                    "HTTP Error Code " + httpResponse.getStatusLine().getStatusCode());
        }
    } catch (UnsupportedEncodingException e) {
        throw new JOFriendFinderUnexpectedException(e);
    } catch (ClientProtocolException e) {
        throw new JOFriendFinderHTTPException(e);
    } catch (IOException e) {
        throw new JOFriendFinderHTTPException(e);
    }
}

From source file:de.geomobile.joined.api.service.JOWebService.java

/**
 * User logout./*from w ww.  ja  v a2s .  c o  m*/
 * 
 * @param userId
 *            The users id.
 * 
 * @param secureToken
 *            The users secureToken.
 * @throws JOFriendFinderUnexpectedException
 * @throws JOFriendFinderServerException
 * @throws JOFriendFinderHTTPException
 */
public void logoutUser(String userId, String secureToken)
        throws JOFriendFinderUnexpectedException, JOFriendFinderServerException, JOFriendFinderHTTPException {
    try {
        HttpClient httpClient = getNewHttpClient();
        HttpPut httpput = new HttpPut(getJoinedServerUrl() + JOConfig.FF_FRIENDS + "/" + userId);
        httpput.addHeader(getAuthenticationHeader(userId, secureToken));
        MultipartEntity entity = new MultipartEntity();
        entity.addPart(JOConfig.REGISTRATION_ID, new StringBody("", Charset.forName(JOConfig.UTF_8)));
        entity.addPart(JOConfig.IS_ACTIVE,
                new StringBody(String.valueOf(false), Charset.forName(JOConfig.UTF_8)));
        httpput.setEntity(entity);
        HttpResponse httpResponse = httpClient.execute(httpput);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            throw new JOFriendFinderServerException();
        } else if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {
            throw new JOFriendFinderUnexpectedException(
                    "HTTP Error Code " + httpResponse.getStatusLine().getStatusCode());
        }
    } catch (UnsupportedEncodingException e) {
        throw new JOFriendFinderUnexpectedException(e);
    } catch (ClientProtocolException e) {
        throw new JOFriendFinderHTTPException(e);
    } catch (IOException e) {
        throw new JOFriendFinderHTTPException(e);
    }
}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

private MultipartEntity getMultiPartEntity(HashMap<String, ContentBody> nameValuePairs) {
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Set<String> fields = nameValuePairs.keySet();
    for (String fieldName : fields) {
        entity.addPart(fieldName, nameValuePairs.get(fieldName));
    }//w  w w . j a va2s  . co  m
    return entity;
}

From source file:de.geomobile.joined.api.service.JOWebService.java

/**
 * Update users current location//w  w  w.ja  v a 2  s  .c  o  m
 * 
 * @param userId
 *            The users id.
 * 
 * @param secureToken
 *            The users secureToken.
 * @param latitude
 * @param longitude
 * @throws JOFriendFinderUnexpectedException
 * @throws JOFriendFinderServerException
 * @throws JOFriendFinderHTTPException
 */
public void updateUser(String userId, String secureToken, double latitude, double longitude)
        throws JOFriendFinderUnexpectedException, JOFriendFinderServerException, JOFriendFinderHTTPException {
    try {
        HttpClient httpClient = getNewHttpClient();
        HttpPut httpput = new HttpPut(getJoinedServerUrl() + JOConfig.FF_FRIENDS + "/" + userId);
        httpput.addHeader(getAuthenticationHeader(userId, secureToken));
        MultipartEntity entity = new MultipartEntity();
        entity.addPart(JOConfig.LATITUDE,
                new StringBody(String.valueOf(latitude), Charset.forName(JOConfig.UTF_8)));
        entity.addPart(JOConfig.LONGITUDE,
                new StringBody(String.valueOf(longitude), Charset.forName(JOConfig.UTF_8)));

        httpput.setEntity(entity);
        HttpResponse httpResponse = httpClient.execute(httpput);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            throw new JOFriendFinderServerException();
        } else if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {
            throw new JOFriendFinderUnexpectedException(
                    "HTTP Error Code " + httpResponse.getStatusLine().getStatusCode());
        }
    } catch (UnsupportedEncodingException e) {
        throw new JOFriendFinderUnexpectedException(e);
    } catch (ClientProtocolException e) {
        throw new JOFriendFinderHTTPException(e);
    } catch (IOException e) {
        throw new JOFriendFinderHTTPException(e);
    }
}

From source file:de.geomobile.joined.api.service.JOWebService.java

/**
 * Send a text message to friend//from   w w w.j  a  v a2s.co  m
 * 
 * @param userId
 *            The users id.
 * 
 * @param secureToken
 *            The users secureToken.
 * @param friendsId
 *            The friends id to send this message
 * @param msg
 *            The text message
 * @return The HashMap String with id and time
 * @throws JOFriendFinderServerException
 * @throws JOFriendFinderUnexpectedException
 * @throws JOFriendFinderHTTPException
 */
public String sendMessage(String userId, String secureToken, String friendsId, String msg)
        throws JOFriendFinderServerException, JOFriendFinderUnexpectedException, JOFriendFinderHTTPException {
    try {
        HttpClient httpClient = getNewHttpClient();
        HttpPost httpPost = new HttpPost(
                getJoinedServerUrl() + JOConfig.FF_MESSAGE + "/" + userId + "/" + friendsId);
        httpPost.addHeader(getAuthenticationHeader(userId, secureToken));
        MultipartEntity entity = new MultipartEntity();
        entity.addPart(JOConfig.TEXT,
                new StringBody(msg, JOConfig.TEXT_PLAIN, Charset.forName(JOConfig.UTF_8)));
        // entity.addPart(Config.ATTACHMENT, new StringBody(placeJson, Config.TEXT_PLAIN, Charset.forName(Config.UTF_8)));
        httpPost.setEntity(entity);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            throw new JOFriendFinderServerException();
        } else if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new JOFriendFinderUnexpectedException(
                    "HTTP Error Code " + httpResponse.getStatusLine().getStatusCode());
        } else {
            return getJsonStringFromResponse(httpResponse);
        }
    } catch (UnsupportedEncodingException e) {
        throw new JOFriendFinderUnexpectedException(e);
    } catch (ClientProtocolException e) {
        throw new JOFriendFinderHTTPException(e);
    } catch (IOException e) {
        throw new JOFriendFinderHTTPException(e);
    }
}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

public WebResponse multipartPostUrl(String sPage, boolean prefix, HashMap<String, ContentBody> nameValuePairs)
        throws UnsupportedEncodingException {
    WebResponse wr = null;/*w w w .j ava 2s .  com*/
    String pageURL = (prefix ? this.urlBase + sPage : sPage);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    Set<String> fields = nameValuePairs.keySet();
    for (String fieldName : fields) {
        entity.addPart(fieldName, nameValuePairs.get(fieldName));
    }
    return doMultiPartPost(pageURL, entity);
}

From source file:de.geomobile.joined.api.service.JOWebService.java

/**
 * Register for FriendFinder users. The nickname and password are mandatory.
 * //www. j ava 2 s. c  om
 * @param name
 *            The users nickname.
 * @param password
 *            The users password.
 * @param profilImage
 *            The users profile image exists.
 * @return the generated attributes userid and secureToken as json object.
 * @throws JOFriendFinderHTTPException
 *             when another exception runs
 * @throws JOFriendFinderUnexpectedException
 * @throws JOFriendFinderServerException
 * @throws JOFriendFinderConflictException
 *             when nickname already exists
 */
public String ffRegister(String name, String password) throws JOFriendFinderHTTPException,
        JOFriendFinderUnexpectedException, JOFriendFinderServerException, JOFriendFinderConflictException {
    try {
        // String hash = getSHA1Hash(name + getJoinedSecretSalt());
        // HttpPost httppost = new HttpPost(getJoinedServerUrl() + Config.FF_REGISTER + Config.HASH + hash);
        HttpPost httppost = new HttpPost(getJoinedServerUrl() + JOConfig.FF_REGISTER + "/" + getJoinedApiKey());
        MultipartEntity entity = new MultipartEntity();
        entity.addPart(JOConfig.NICKNAME, new StringBody(name, Charset.forName(JOConfig.UTF_8)));
        entity.addPart(JOConfig.PASSWORD,
                new StringBody(getSHA1Hash(password + name), Charset.forName(JOConfig.UTF_8)));
        // entity.addPart(Config.IMAGE_KEY, new FileBody(new File(Config.MEDIA_PATH + Config.IMAGE_PNG)));
        // entity.addPart(Config.IMAGE_HASH, new StringBody(calculateHash(Config.MEDIA_PATH + Config.IMAGE_PNG), Charset.forName(Config.UTF_8)));
        httppost.setEntity(entity);

        HttpClient httpClient = getNewHttpClient();
        HttpResponse httpResponse = httpClient.execute(httppost);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            throw new JOFriendFinderServerException();
        } else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CONFLICT) {
            throw new JOFriendFinderConflictException();
        } else if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new JOFriendFinderUnexpectedException(
                    "HTTP Error Code " + httpResponse.getStatusLine().getStatusCode());
        } else {
            return getJsonStringFromResponse(httpResponse);
        }
    } catch (GeneralSecurityException e) {
        throw new JOFriendFinderUnexpectedException(e);
    } catch (UnsupportedEncodingException e) {
        throw new JOFriendFinderUnexpectedException(e);
    } catch (ClientProtocolException e) {
        throw new JOFriendFinderHTTPException(e);
    } catch (IOException e) {
        throw new JOFriendFinderHTTPException(e);
    } catch (Exception e) {
        throw new JOFriendFinderUnexpectedException(e);
    }
}

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 {/*  w w  w .  ja v a 2  s.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) {

        }
    }
}