Example usage for org.apache.http.entity.mime.content StringBody StringBody

List of usage examples for org.apache.http.entity.mime.content StringBody StringBody

Introduction

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

Prototype

public StringBody(final String text) throws UnsupportedEncodingException 

Source Link

Usage

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

public HashMap<String, ContentBody> getAuthorizeFormFieldValues(String sBody)
        throws UnsupportedEncodingException {
    HashMap<String, ContentBody> nvp = new HashMap<String, ContentBody>();
    Document doc = Jsoup.parse(sBody);
    if (!doc.select("input[name=client_id]").isEmpty()) {
        nvp.put("client_id", new StringBody(getItemAttributeValue(doc, "input[name=client_id]", "value")));
        nvp.put("state", new StringBody(getItemAttributeValue(doc, "input[name=state]", "value")));
        nvp.put("time", new StringBody(getItemAttributeValue(doc, "input[name=time]", "value")));
        nvp.put("nonce", new StringBody(getItemAttributeValue(doc, "input[name=nonce]", "value")));
        nvp.put("form.actions.authorize",
                new StringBody(getItemAttributeValue(doc, "input[name=form.actions.authorize]", "value")));
    }//from w ww  .j  a  v a2s .  c  om
    return nvp;

}

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;//  ww w. j a va2 s  .c  om
    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.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

public WebResponse multipartPostUrl(String sPage, boolean prefix, List<BasicNameValuePair> nameValuePairs)
        throws UnsupportedEncodingException {
    WebResponse wr = null;//from w ww .  jav a 2 s .c  o m
    String pageURL = (prefix ? this.urlBase + sPage : sPage);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (BasicNameValuePair nv : nameValuePairs) {
        entity.addPart(nv.getName(), new StringBody(nv.getValue()));
    }

    return this.doMultiPartPost(pageURL, entity);
    /*
    HttpPost webPost = new HttpPost(pageURL);
    webPost.setEntity(entity);
    HttpResponse response = null ;
    try {
    response = client.execute(webPost);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String sBody = responseHandler.handleResponse(response);
    wr = new WebResponse(response.getStatusLine().getStatusCode(), sBody);
    } catch (IOException ex) {
    log.error(ex.getMessage(), ex);
    } finally {
    if (response != null) {
        consumeContent(
            response.getEntity()
        );
    }
    }
    return wr; */
}

From source file:connection.ChaperOnConnection.java

private HttpPost GetPostHTTP(String email, String password, String firstname, String username, String imagePath,
        String street, String apartment, String city, String postal, String country, String lastname,
        String description, int rideType, double lattitude, double longitude, String phone, int availableseats,
        String licenseImage) {//from ww w .j  a v a 2 s .  c om
    Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
    Bitmap bitmap2 = BitmapFactory.decodeFile(licenseImage);
    HttpPost request = new HttpPost(REGISTER_URL);
    String param = "{\"phone\":\"" + phone + "\",\"email\":\"" + email + "\",\"password\": \"" + password
            + "\",\"username\": \"" + username + "\",\"availableSeats\":" + availableseats + ",\"type\": "
            + rideType + ",\"lattitude\": " + lattitude + ",\"longtitude\": " + longitude + ",\"street\": \""
            + street + "\",\"appartment\": \"" + apartment + "\",\"city\": \"" + city + "\",\"zip\": \""
            + postal + "\",\"country\": \"" + country + "\",\"lname\": \"" + lastname + "\",\"description\": \""
            + description + "\",\"fname\": \"" + firstname + "\"}";
    String BOUNDARY = "---------------------------41184676334";
    request.setHeader("enctype", "multipart/form-data; boundary=" + BOUNDARY);
    request.setHeader("app-id", "appid");
    request.setHeader("app-key", "appkey");

    MultipartEntityBuilder entity = MultipartEntityBuilder.create();

    try {
        entity.addPart("data", new StringBody(param));

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, bos);
        bitmap2.compress(Bitmap.CompressFormat.JPEG, 70, bos2);

        InputStream in = new ByteArrayInputStream(bos.toByteArray());
        InputStream in2 = new ByteArrayInputStream(bos2.toByteArray());

        ContentBody image = new InputStreamBody(in, "image/jpeg");
        ContentBody image2 = new InputStreamBody(in2, "image/jpeg");
        entity.addPart("image", image);
        entity.addPart("licenceimage", image2);

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    request.setEntity(entity.build());
    return request;
}

From source file:org.protocoderrunner.apprunner.api.PNetwork.java

@ProtocoderScript
@APIMethod(description = "Simple http post request. It needs an object to be sent. If an element of the object contains the key file then it will try to upload the resource indicated in the value as Uri ", example = "")
@APIParam(params = { "url", "params", "function(responseString)" })
public void httpPost(String url, Object object, final HttpPostCB callbackfn) {
    final HttpClient httpClient = new DefaultHttpClient();
    final HttpContext localContext = new BasicHttpContext();
    final HttpPost httpPost = new HttpPost(url);

    Gson g = new Gson();
    JsonArray q = g.toJsonTree(object).getAsJsonArray();

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    for (int i = 0; i < q.size(); i++) {
        Set<Entry<String, JsonElement>> set = q.get(i).getAsJsonObject().entrySet();

        // go through elements
        String name = "";
        String content = "";
        String type = "";
        for (Object element : set) {
            Entry<String, JsonElement> entry = (Entry<String, JsonElement>) element;
            if (entry.getKey().equals("name")) {
                name = entry.getValue().getAsString();
            } else if (entry.getKey().equals("content")) {
                content = entry.getValue().getAsString();
            } else if (entry.getKey().equals("type")) {
                type = entry.getValue().getAsString();
            }//  ww  w  .j  ava 2  s  . c o  m
        }

        // create the multipart
        if (type.contains("file")) {
            File f = new File(
                    ProjectManager.getInstance().getCurrentProject().getStoragePath() + "/" + content);
            ContentBody cbFile = new FileBody(f);
            entity.addPart(name, cbFile);
        } else if (type.contains("text")) { // Normal string data
            try {
                entity.addPart(name, new StringBody(content));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    // send
    httpPost.setEntity(entity);
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                HttpResponse response = httpClient.execute(httpPost, localContext);
                callbackfn.event(response.getStatusLine().toString());
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

From source file:project.cs.netinfservice.netinf.node.resolution.NameResolutionService.java

/**
 * Creates an HTTP POST representation of a NetInf PUBLISH message.
 *
 * @param io/*w w w  . j av  a 2 s. c om*/
 *     The information object to publish
 * @return
 *     A HttpPost representing the NetInf PUBLISH message
 * @throws UnsupportedEncodingException
 *     In case the encoding is not supported
 */
private HttpPost createPublish(InformationObject io) throws UnsupportedEncodingException {
    // Extracting attributes from IO's identifier
    String hashAlg = getHashAlg(io.getIdentifier());
    String hash = getHash(io.getIdentifier());
    String contentType = getContentType(io.getIdentifier());
    String meta = getMetadata(io.getIdentifier());
    String bluetoothMac = getBluetoothMac(io);
    String filePath = getFilePath(io);

    // Creates a new post. Looks like http://host:port/netinfproto/publish
    HttpPost post = new HttpPost(HTTP + getHost() + ":" + getPort() + "/netinfproto/publish");

    // Create a multipart entity
    MultipartEntity entity = new MultipartEntity();

    // ni:///hashAlgorithm;hash?ct=CONTENT_TYPE
    StringBody uri = new StringBody("ni:///" + hashAlg + ";" + hash + "?ct=" + contentType);
    entity.addPart("URI", uri);

    // Create a new message id
    StringBody msgid = new StringBody(Integer.toString(mRandomGenerator.nextInt(MSG_ID_MAX)));
    entity.addPart("msgid", msgid);

    // Add a locator
    if (bluetoothMac != null) {
        StringBody l = new StringBody(bluetoothMac);
        entity.addPart("loc1", l);
    }

    // Add metadata (ext)
    if (meta != null) {
        StringBody ext = new StringBody(meta.toString());
        entity.addPart("ext", ext);
    }

    // Add fullput and octets
    if (filePath != null) {
        StringBody fullPut = new StringBody("true");
        entity.addPart("fullPut", fullPut);
        FileBody octets = new FileBody(new File(filePath));
        entity.addPart("octets", octets);
    }

    // Add form type
    StringBody rform = new StringBody("json");
    entity.addPart("rform", rform);

    //        // Used to print the message sent to the NRS
    //        try {
    //            entity.writeTo(System.out);
    //        } catch (IOException e) {
    //            Log.e(TAG, "Failed to write MultipartEntity to System.out");
    //        }

    // Set attributes to HTTP Post object
    post.setEntity(entity);

    // Return HTTP Post object with all attributes
    return post;
}

From source file:fm.smart.r1.activity.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;//from w  w w . jav a 2 s.  c om
    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 = Main.username(this) + ":" + Main.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:com.siahmsoft.soundroid.sdk7.provider.tracks.TracksStore.java

public void shareTrack(String idTrack, ArrayList<String> mails, ResultListener<Track> listener) {
    final Uri uri = buildShareTrackQuery(idTrack);

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

    for (String mail : mails) {
        if (mail != null && !"".equals(mail)) {
            ContentBody sharedTo;//from   www.  ja v  a  2s . co m
            try {
                sharedTo = new StringBody(mail.trim());
                entity.addPart("track[shared_to][emails][][address]", sharedTo);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    final HttpPut put = new HttpPut(uri.toString());
    signRequest(put);
    put.setEntity(entity);

    try {
        executeRequestNotSigned(put, new ResponseHandler() {
            public void handleResponse(InputStream in) throws IOException {
                parseSingleResponse(in, new ResponseParserSingle() {
                    @Override
                    public void parseResponse(JSONObject parser) throws JSONException {
                        int i = 0;
                        i++;
                    }
                });
            }
        });

    } catch (IOException e) {
        android.util.Log.e(LOG_TAG, "Could not perform search with query: ", e);
        listener.onError(e);
    }

}

From source file:org.opencastproject.capture.impl.CaptureAgentImpl.java

/**
 * Sends a file to the REST ingest service.
 * //from w w  w .  j  av a 2 s  .c  om
 * @param recID
 *          The ID for the recording to be ingested.
 * @return The status code for the http post, or one of a number of error values. The error values are as follows: -1:
 *         Unable to ingest because the recording id does not exist -2: Invalid ingest url -3: Invalid ingest url -4:
 *         Invalid ingest url -5: Unable to open media package
 */
public int ingest(String recID) {
    logger.info("Ingesting recording: {}", recID);
    AgentRecording recording = pendingRecordings.get(recID);

    if (recording == null) {
        logger.error("[ingest] Recording {} not found!", recID);
        return -1;
    }

    // Find all the available ingest services
    List<ServiceRegistration> ingestServices = null;
    URL url = null;
    try {
        ingestServices = serviceRegistry.getServiceRegistrationsByLoad("org.opencastproject.ingest");
        if (ingestServices.size() == 0) {
            logger.warn("Unable to ingest media because no ingest service is available");
            return -4;
        }

        // Take the least loaded one (first in line)
        ServiceRegistration ingestService = ingestServices.get(0);
        url = new URL(
                UrlSupport.concat(ingestService.getHost(), ingestService.getPath() + "/addZippedMediaPackage"));
    } catch (ServiceRegistryException e) {
        logger.warn("Unable to ingest media because communication with the remote service registry failed.", e);
        return -4;
    } catch (MalformedURLException e) {
        logger.warn("Malformed URL for ingest target.");
        return -3;
    }

    File fileDesc = new File(recording.getBaseDir(), CaptureParameters.ZIP_NAME);

    // Set the file as the body of the request
    MultipartEntity entities = new MultipartEntity();
    // Check to see if the properties have an alternate workflow definition attached
    String workflowDefinitionId = recording.getProperty(CaptureParameters.INGEST_WORKFLOW_DEFINITION);
    String workflowInstance = recording.getID();
    // Copy appropriate keys from the properties so they can be passed to the REST endpoint separately
    Set<Object> keys = recording.getProperties().keySet();
    for (Object o : keys) {
        String key = (String) o;
        if (key.contains("org.opencastproject.workflow.config.")) {
            try {
                String configKey = key.replaceFirst("org\\.opencastproject\\.workflow\\.config\\.", "");
                entities.addPart(configKey, new StringBody(recording.getProperty(key)));
            } catch (UnsupportedEncodingException e) {
                logger.warn("Unable to attach property {} to POST.  Exception message: {}.", key,
                        e.getMessage());
            }
        }
    }

    try {
        if (workflowDefinitionId != null) {
            entities.addPart("workflowDefinitionId",
                    new StringBody(workflowDefinitionId, Charset.forName("UTF-8")));
        }
        if (workflowInstance != null) {
            entities.addPart("workflowInstanceId", new StringBody(workflowInstance, Charset.forName("UTF-8")));
        }
        entities.addPart(fileDesc.getName(),
                new InputStreamBody(new FileInputStream(fileDesc), fileDesc.getName()));
    } catch (FileNotFoundException ex) {
        logger.error("Could not find zipped mediapackage " + fileDesc.getAbsolutePath());
        return -5;
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("This system does not support UTF-8", e);
    }

    logger.debug("Ingest URL is " + url.toString());
    HttpPost postMethod = new HttpPost(url.toString());
    postMethod.setEntity(entities);

    setRecordingState(recID, RecordingState.UPLOADING);

    // Send the file
    HttpResponse response = null;
    int retValue = -1;
    try {
        logger.debug("Sending the file " + fileDesc.getAbsolutePath() + " with a size of " + fileDesc.length());
        response = client.execute(postMethod);
    } catch (TrustedHttpClientException e) {
        logger.error("Unable to ingest recording {}, message reads: {}.", recID, e.getMessage());
    } catch (NullPointerException e) {
        logger.error("Unable to ingest recording {}, null pointer exception!", recID);
    } finally {
        if (response != null) {
            retValue = response.getStatusLine().getStatusCode();
            client.close(response);
        } else {
            retValue = -1;
        }
    }

    if (retValue == HttpURLConnection.HTTP_OK) {
        setRecordingState(recID, RecordingState.UPLOAD_FINISHED);
    } else {
        setRecordingState(recID, RecordingState.UPLOAD_ERROR);
    }

    serializeRecording(recID);
    if (retValue == HttpURLConnection.HTTP_OK) {
        removeZipFile(recording);
        completedRecordings.put(recID, recording);
        pendingRecordings.remove(recID);
    }
    return retValue;
}

From source file:com.siahmsoft.soundroid.sdk7.provider.tracks.TracksStore.java

public void uploadTrack(Bundle bundle, ResultListener<Track> listener) {

    Track track = TracksStore.Track.fromBundle(bundle);

    SystemClock.sleep(1500);//from w w w.j  a  v a2s  . c  o m

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

        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 && !"".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");
            signRequest(filePost);
            filePost.setEntity(entity);

            executeRequestNotSigned(filePost, new ResponseHandler() {
                public void handleResponse(InputStream in) throws IOException {
                    parseSingleResponse(in, new ResponseParserSingle() {
                        @Override
                        public void parseResponse(JSONObject parser) throws JSONException {
                            int i = 0;
                            i++;
                        }
                    });
                }
            });
        } catch (Exception e) {

        }
        /* mBoundUploadService = Soundroid.getUploadService();
        mBoundUploadService.uploadTrack(track);*/
    } 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");
            signRequest(filePut);

            filePut.setEntity(entity);

            executeRequestNotSigned(filePut, new ResponseHandler() {
                public void handleResponse(InputStream in) throws IOException {
                    parseSingleResponse(in, new ResponseParserSingle() {
                        @Override
                        public void parseResponse(JSONObject parser) throws JSONException {
                            int i = 0;
                            i++;
                        }
                    });
                }
            });
        } catch (Exception e) {

        }
    }
}