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:functionaltests.RestSchedulerPushPullFileTest.java

public void testIt(String spaceName, String spacePath, String destPath, boolean encode) throws Exception {
    File testPushFile = RestFuncTHelper.getDefaultJobXmlfile();
    // you can test pushing pulling a big file :
    // testPushFile = new File("path_to_a_big_file");
    File destFile = new File(new File(spacePath, destPath), testPushFile.getName());
    if (destFile.exists()) {
        destFile.delete();//from w  w w  .  j  a  va 2s  . c  om
    }

    // PUSHING THE FILE
    String pushfileUrl = getResourceUrl("dataspace/" + spaceName + "/"
            + (encode ? URLEncoder.encode(destPath, "UTF-8") : destPath.replace("\\", "/")));
    // either we encode or we test human readable path (with no special character inside)

    HttpPost reqPush = new HttpPost(pushfileUrl);
    setSessionHeader(reqPush);
    // we push a xml job as a simple test

    MultipartEntity multipartEntity = new MultipartEntity();
    multipartEntity.addPart("fileName", new StringBody(testPushFile.getName()));
    multipartEntity.addPart("fileContent", new InputStreamBody(FileUtils.openInputStream(testPushFile),
            MediaType.APPLICATION_OCTET_STREAM, null));
    reqPush.setEntity(multipartEntity);
    HttpResponse response = executeUriRequest(reqPush);

    System.out.println(response.getStatusLine());
    assertHttpStatusOK(response);
    Assert.assertTrue(destFile + " exists for " + spaceName, destFile.exists());

    Assert.assertTrue("Original file and result are equals for " + spaceName,
            FileUtils.contentEquals(testPushFile, destFile));

    // LISTING THE TARGET DIRECTORY
    String pullListUrl = getResourceUrl("dataspace/" + spaceName + "/"
            + (encode ? URLEncoder.encode(destPath, "UTF-8") : destPath.replace("\\", "/")));

    HttpGet reqPullList = new HttpGet(pullListUrl);
    setSessionHeader(reqPullList);

    HttpResponse response2 = executeUriRequest(reqPullList);

    System.out.println(response2.getStatusLine());
    assertHttpStatusOK(response2);

    InputStream is = response2.getEntity().getContent();
    List<String> lines = IOUtils.readLines(is);
    HashSet<String> content = new HashSet<>(lines);
    System.out.println(lines);
    Assert.assertTrue("Pushed file correctly listed", content.contains(testPushFile.getName()));

    // PULLING THE FILE
    String pullfileUrl = getResourceUrl("dataspace/" + spaceName + "/"
            + (encode ? URLEncoder.encode(destPath + "/" + testPushFile.getName(), "UTF-8")
                    : destPath.replace("\\", "/") + "/" + testPushFile.getName()));

    HttpGet reqPull = new HttpGet(pullfileUrl);
    setSessionHeader(reqPull);

    HttpResponse response3 = executeUriRequest(reqPull);

    System.out.println(response3.getStatusLine());
    assertHttpStatusOK(response3);

    InputStream is2 = response3.getEntity().getContent();

    File answerFile = tmpFolder.newFile();
    FileUtils.copyInputStreamToFile(is2, answerFile);

    Assert.assertTrue("Original file and result are equals for " + spaceName,
            FileUtils.contentEquals(answerFile, testPushFile));

    // DELETING THE HIERARCHY
    String rootPath = destPath.substring(0, destPath.contains("/") ? destPath.indexOf("/") : destPath.length());
    String deleteUrl = getResourceUrl("dataspace/" + spaceName + "/"
            + (encode ? URLEncoder.encode(rootPath, "UTF-8") : rootPath.replace("\\", "/")));
    HttpDelete reqDelete = new HttpDelete(deleteUrl);
    setSessionHeader(reqDelete);

    HttpResponse response4 = executeUriRequest(reqDelete);

    System.out.println(response4.getStatusLine());

    assertHttpStatusOK(response4);

    Assert.assertTrue(destFile + " still exist", !destFile.exists());
}

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 ww  .j ava  2 s .  com

            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:at.ac.tuwien.big.testsuite.impl.validator.WaiValidator.java

@Override
public ValidationResult validate(File fileToValidate, String exerciseId) throws Exception {
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    HttpPost request = new HttpPost("http://localhost:8080/" + contextPath + "/checker/index.php");
    List<ValidationResultEntry> validationResultEntries = new ArrayList<>();

    try {/*  www.j  a  va2s  . c o  m*/
        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart("uri", new StringBody(""));
        multipartEntity.addPart("MAX_FILE_SIZE", new StringBody("52428800"));
        multipartEntity.addPart("uploadfile", new FileBody(fileToValidate, "text/html"));
        multipartEntity.addPart("validate_file", new StringBody("Check It"));
        multipartEntity.addPart("pastehtml", new StringBody(""));
        multipartEntity.addPart("radio_gid[]", new StringBody("8"));
        multipartEntity.addPart("checkbox_gid[]", new StringBody("8"));
        multipartEntity.addPart("rpt_format", new StringBody("1"));

        request.setEntity(multipartEntity);
        Document doc = httpClient.execute(request, new DomResponseHandler(httpClient, request), httpContext);
        Element errorsContainer = DomUtils.byId(doc.getDocumentElement(), "AC_errors");

        String title = "";
        StringBuilder descriptionSb = new StringBuilder();
        boolean descriptionStarted = false;

        for (Element e : DomUtils.asList(errorsContainer.getChildNodes())) {
            if ("h3".equals(e.getTagName())) {
                if (descriptionStarted) {
                    validationResultEntries.add(new DefaultValidationResultEntry(title,
                            descriptionSb.toString(), ValidationResultEntryType.ERROR));
                }

                title = e.getTextContent();
                descriptionSb.setLength(0);
                descriptionStarted = false;
            } else if ("div".equals(e.getTagName()) && e.getAttribute("class").contains("gd_one_check")) {
                if (descriptionStarted) {
                    descriptionSb.append('\n');
                }

                if (extractDescription(e, descriptionSb)) {
                    descriptionStarted = true;
                }
            }
        }

        if (descriptionStarted) {
            validationResultEntries.add(new DefaultValidationResultEntry(title, descriptionSb.toString(),
                    ValidationResultEntryType.ERROR));
        }
    } finally {
        request.releaseConnection();
    }

    return new DefaultValidationResult("WAI Validation", fileToValidate.getName(),
            new DefaultValidationResultType("WAI"), validationResultEntries);
}

From source file:interactivespaces.util.web.HttpClientHttpContentCopier.java

/**
 * Perform the actual content copy./*from   ww w  . ja v a 2 s.  com*/
 *
 * @param destinationUri
 *          URI for the destination
 * @param sourceParameterName
 *          the parameter name in the HTTP form post for the content
 * @param params
 *          the parameters to be included, can be {@code null}
 * @param contentBody
 *          the content to be sent
 */
private void doCopyTo(String destinationUri, String sourceParameterName, Map<String, String> params,
        AbstractContentBody contentBody) {
    HttpEntity entity = null;
    try {
        HttpPost httpPost = new HttpPost(destinationUri);

        MultipartEntity mpEntity = new MultipartEntity();

        mpEntity.addPart(sourceParameterName, contentBody);

        if (params != null) {
            for (Entry<String, String> entry : params.entrySet()) {
                mpEntity.addPart(entry.getKey(), new StringBody(entry.getValue()));
            }
        }

        httpPost.setEntity(mpEntity);

        HttpResponse response = httpClient.execute(httpPost);

        entity = response.getEntity();

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new SimpleInteractiveSpacesException(
                    String.format("Server returned bad status code %d for source URI %s during HTTP copy",
                            statusCode, destinationUri));
        }
    } catch (InteractiveSpacesException e) {
        throw e;
    } catch (Exception e) {
        throw new InteractiveSpacesException(
                String.format("Could not send file to destination URI %s during HTTP copy", destinationUri), e);
    } finally {
        if (entity != null) {
            try {
                EntityUtils.consume(entity);
            } catch (IOException e) {
                throw new InteractiveSpacesException(String
                        .format("Could not consume entity content for %s during HTTP copy", destinationUri), e);
            }
        }
    }
}

From source file:com.ushahidi.android.app.net.CommentHttpClient.java

/**
 * Upload files to server 0 - success, 1 - missing parameter, 2 - invalid
 * parameter, 3 - post failed, 5 - access denied, 6 - access limited, 7 - no
 * data, 8 - api disabled, 9 - no task found, 10 - json is wrong
 *///from w  w  w .  j a v  a  2 s  .c  o  m
public boolean PostFileUpload(String URL, HashMap<String, String> params) throws IOException {
    log("PostFileUpload(): upload file to server.");

    apiUtils.updateDomain();
    entity = new MultipartEntity();
    // Dipo Fix
    try {
        // wrap try around because this constructor can throw Error
        final HttpPost httpost = new HttpPost(URL);

        if (params != null) {

            entity.addPart("task", new StringBody("comments"));
            entity.addPart("action", new StringBody("add"));
            entity.addPart("comment_author", new StringBody(params.get("comment_author")));
            entity.addPart("comment_description",
                    new StringBody(params.get("comment_description"), Charset.forName("UTF-8")));
            entity.addPart("comment_email",
                    new StringBody(params.get("comment_email"), Charset.forName("UTF-8")));
            if ((params.get("incident_id") != null) && (Integer.valueOf(params.get("incident_id")) != 0))
                entity.addPart("incident_id", new StringBody(params.get("incident_id")));

            if ((params.get("checkin_id") != null) && (Integer.valueOf(params.get("checkin_id")) != 0))
                entity.addPart("checkin_id",
                        new StringBody(params.get("checkin_id"), Charset.forName("UTF-8")));
            // NEED THIS NOW TO FIX ERROR 417
            httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
            httpost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpost);
            Preferences.httpRunning = false;

            HttpEntity respEntity = response.getEntity();
            if (respEntity != null) {
                InputStream serverInput = respEntity.getContent();
                if (serverInput != null) {
                    // TODO:: get the status confirmation code to work
                    //int status = ApiUtils.extractPayloadJSON(GetText(serverInput));
                    return true;
                }

                return false;
            }
        }

    } catch (MalformedURLException ex) {
        log("PostFileUpload(): MalformedURLException", ex);

        return false;
        // fall through and return false
    } catch (IllegalArgumentException ex) {
        log("IllegalArgumentException", ex);
        // invalid URI
        return false;
    } catch (IOException e) {
        log("IOException", e);
        // timeout
        return false;
    }
    return false;
}

From source file:com.auditmark.jscrambler.client.JScrambler.java

private Object httpRequest(String requestMethod, String resourcePath, Map params)
        throws IOException, Exception {

    String signedData = null, urlQueryPart = null;

    if (requestMethod.toUpperCase().equals("POST") && params.isEmpty()) {
        throw new IllegalArgumentException("Parameters missing for POST request.");
    }/*  www .  j  av a2s  . co  m*/

    String[] files = null;

    if (params == null) {
        params = new TreeMap();
    } else {
        if (params.get("files") instanceof String) {
            files = new String[] { (String) params.get("files") };
            params.put("files", files);
        } else if (params.get("files") instanceof String[]) {
            files = (String[]) params.get("files");
        }
        params = new TreeMap(params);
    }

    if (requestMethod.toUpperCase().equals("POST")) {
        signedData = signedQuery(requestMethod, resourcePath, params, null);
    } else {
        urlQueryPart = "?" + signedQuery(requestMethod, resourcePath, params, null);
    }

    // http client
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = null;

    try {
        if (signedData != null && requestMethod.toUpperCase().equals("POST")) {
            HttpPost httppost = new HttpPost(
                    apiURL() + resourcePath + (urlQueryPart != null ? urlQueryPart : ""));
            MultipartEntity reqEntity = new MultipartEntity();

            if (files != null) {
                int n = 0;
                for (String filename : files) {
                    FileBody fb = new FileBody(new File(filename));
                    reqEntity.addPart("file_" + n++, fb);
                }
            }

            for (String param : (Set<String>) params.keySet()) {
                if (param.equals("files") || param.startsWith("file_")) {
                    continue;
                }
                if (params.get(param) instanceof String) {
                    reqEntity.addPart(param, new StringBody((String) params.get(param)));
                }
            }

            httppost.setEntity(reqEntity);
            response = httpclient.execute(httppost);

        } else if (requestMethod.toUpperCase().equals("GET")) {
            HttpGet request = new HttpGet(apiURL() + resourcePath + (urlQueryPart != null ? urlQueryPart : ""));
            response = httpclient.execute(request);
        } else if (requestMethod.toUpperCase().equals("DELETE")) {
            HttpDelete request = new HttpDelete(
                    apiURL() + resourcePath + (urlQueryPart != null ? urlQueryPart : ""));
            response = httpclient.execute(request);
        } else {
            throw new Exception("Invalid request method.");
        }

        HttpEntity httpEntity = response.getEntity();

        // if GET Zip archive
        if (requestMethod.toUpperCase().equals("GET") && resourcePath.toLowerCase().endsWith(".zip")
                && response.getStatusLine().getStatusCode() == 200) {
            // Return inputstream
            return httpEntity.getContent();
        }
        // Otherwise return string
        return EntityUtils.toString(httpEntity, "UTF-8");

    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw e;
    }
}

From source file:net.wm161.microblog.lib.backends.statusnet.HTTPAPIRequest.java

protected String getData(URI location) throws APIException {
    Log.d("HTTPAPIRequest", "Downloading " + location);
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(location);
    client.addRequestInterceptor(preemptiveAuth, 0);

    client.getParams().setBooleanParameter("http.protocol.expect-continue", false);

    if (!m_params.isEmpty()) {
        MultipartEntity params = new MultipartEntity();
        for (Entry<String, Object> item : m_params.entrySet()) {
            Object value = item.getValue();
            ContentBody data;//from   w w  w . j av a2s  .c o m
            if (value instanceof Attachment) {
                Attachment attachment = (Attachment) value;
                try {
                    data = new InputStreamBody(attachment.getStream(), attachment.contentType(),
                            attachment.name());
                    Log.d("HTTPAPIRequest",
                            "Found a " + attachment.contentType() + " attachment named " + attachment.name());
                } catch (FileNotFoundException e) {
                    getRequest().setError(ErrorType.ERROR_ATTACHMENT_NOT_FOUND);
                    throw new APIException();
                } catch (IOException e) {
                    getRequest().setError(ErrorType.ERROR_ATTACHMENT_NOT_FOUND);
                    throw new APIException();
                }
            } else {
                try {
                    data = new StringBody(value.toString());
                } catch (UnsupportedEncodingException e) {
                    getRequest().setError(ErrorType.ERROR_INTERNAL);
                    throw new APIException();
                }
            }
            params.addPart(item.getKey(), data);
        }
        post.setEntity(params);
    }

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(m_api.getAccount().getUser(),
            m_api.getAccount().getPassword());
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

    HttpResponse req;
    try {
        req = client.execute(post);
    } catch (ClientProtocolException e3) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN);
        throw new APIException();
    } catch (IOException e3) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_FAILED);
        throw new APIException();
    }

    InputStream result;
    try {
        result = req.getEntity().getContent();
    } catch (IllegalStateException e1) {
        getRequest().setError(ErrorType.ERROR_INTERNAL);
        throw new APIException();
    } catch (IOException e1) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN);
        throw new APIException();
    }

    InputStreamReader in = null;
    int status;
    in = new InputStreamReader(result);
    status = req.getStatusLine().getStatusCode();
    Log.d("HTTPAPIRequest", "Got status code of " + status);
    setStatusCode(status);
    if (status >= 300 || status < 200) {
        getRequest().setError(ErrorType.ERROR_SERVER);
        Log.w("HTTPAPIRequest", "Server code wasn't 2xx, got " + m_status);
        throw new APIException();
    }

    int totalSize = -1;
    if (req.containsHeader("Content-length"))
        totalSize = Integer.parseInt(req.getFirstHeader("Content-length").getValue());

    char[] buffer = new char[1024];
    //2^17 = 131072.
    StringBuilder contents = new StringBuilder(131072);
    try {
        int size = 0;
        while ((totalSize > 0 && size < totalSize) || totalSize == -1) {
            int readSize = in.read(buffer);
            size += readSize;
            if (readSize == -1)
                break;
            if (totalSize >= 0)
                getRequest().publishProgress(new APIProgress((size / totalSize) * 5000));
            contents.append(buffer, 0, readSize);
        }
    } catch (IOException e) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN);
        throw new APIException();
    }
    return contents.toString();
}

From source file:com.ctctlabs.ctctwsjavalib.CTCTConnection.java

/**
 * Perform a multipart post request to the web service
 * @param link     URL to perform the post request
 * @param content  the string part/*from  w  w  w . j  a  v  a2s.c  o  m*/
 * @param baData   the byte array part
 * @param fileName the file name in the byte array part
 * @return response entity content returned by the web service
 * @throws ClientProtocolException
 * @throws IOException
 * @author CL Kim
 */
InputStream doPostMultipartRequest(String link, String content, byte[] baData, String fileName)
        throws ClientProtocolException, IOException {
    HttpPost httppost = new HttpPost(link);

    StringBody sbody = new StringBody(content);
    FormBodyPart fbp1 = new FormBodyPart("imageatomxmlpart", sbody);
    fbp1.addField("Content-Type", "application/atom+xml");
    //fbp1.addField("Accept", "application/atom+xml");

    ByteArrayBody babody = new ByteArrayBody(baData, fileName);
    FormBodyPart fbp2 = new FormBodyPart("imagejpegpart", babody);
    fbp2.addField("Content-Type", "image/jpeg");
    fbp2.addField("Transfer-Encoding", "binary");
    //fbp2.addField("Accept", "application/atom+xml");

    MultipartEntity reqEntity = new MultipartEntity(); // HttpMultipartMode.STRICT is default, cannot be HttpMultipartMode.BROWSER_COMPATIBLE
    reqEntity.addPart(fbp1);
    reqEntity.addPart(fbp2);
    httppost.setEntity(reqEntity);
    if (accessToken != null)
        httppost.setHeader("Authorization", "Bearer " + accessToken); // for OAuth2.0
    HttpResponse response = httpclient.execute(httppost);

    if (response != null) {
        responseStatusCode = response.getStatusLine().getStatusCode();
        responseStatusReason = response.getStatusLine().getReasonPhrase();
        // If receive anything but a 201 status, return a null input stream
        if (responseStatusCode == HttpStatus.SC_CREATED) {
            return response.getEntity().getContent();
        }
        return null;
    } else {
        responseStatusCode = 0; // reset to initial default
        responseStatusReason = null; // reset to initial default
        return null;
    }
}

From source file:net.yama.android.managers.connection.OAuthConnectionManager.java

/**
 * Special request for photo upload since OAuth doesn't handle multipart/form-data
 *//*from  w w w.jav a 2 s .com*/
public String uploadPhoto(WritePhotoRequest request) throws ApplicationException {

    String responseString = null;
    try {
        OAuthAccessor accessor = new OAuthAccessor(OAuthConnectionManager.consumer);
        accessor.accessToken = ConfigurationManager.instance.getAccessToken();
        accessor.tokenSecret = ConfigurationManager.instance.getAccessTokenSecret();

        String tempImagePath = request.getParameterMap().remove(Constants.TEMP_IMAGE_FILE_PATH);
        String eventId = request.getParameterMap().remove(Constants.EVENT_ID_KEY);

        ArrayList<Map.Entry<String, String>> params = new ArrayList<Map.Entry<String, String>>();
        convertRequestParamsToOAuth(params, request.getParameterMap());
        OAuthMessage message = new OAuthMessage(request.getMethod(), request.getRequestURL(), params);
        message.addRequiredParameters(accessor);
        List<Map.Entry<String, String>> oAuthParams = message.getParameters();
        String url = OAuth.addParameters(request.getRequestURL(), oAuthParams);

        HttpPost post = new HttpPost(url);
        File photoFile = new File(tempImagePath);
        FileBody photoContentBody = new FileBody(photoFile);
        StringBody eventIdBody = new StringBody(eventId);

        HttpClient client = new DefaultHttpClient();
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT);
        reqEntity.addPart(Constants.PHOTO, photoContentBody);
        reqEntity.addPart(Constants.EVENT_ID_KEY, eventIdBody);
        post.setEntity(reqEntity);

        HttpResponse response = client.execute(post);
        HttpEntity resEntity = response.getEntity();
        responseString = EntityUtils.toString(resEntity);

    } catch (Exception e) {
        Log.e("OAuthConnectionManager", "Exception in uploadPhoto()", e);
        throw new ApplicationException(e);
    }

    return responseString;
}

From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.NaturalLanguageClassifier.java

/**
 * Sends data to create and train a classifier, and returns information about the new
 * classifier. The status has the value of `Training` when the operation is
 * successful, and might remain at this status for a while.
 * /*from   w  ww  .j  a  v  a2s .  c  o m*/
 * @param name
 *            the classifier name
 * @param language
 *            IETF primary language for the classifier
 * @param trainingData
 *            The set of questions and their "keys" used to adapt a system to a domain
 *            (the ground truth)
 * @return the classifier
 * @see Classifier
 */
public Classifier createClassifier(final String name, final String language,
        final List<TrainingData> trainingData) {
    if (trainingData == null || trainingData.isEmpty())
        throw new IllegalArgumentException("trainingData can not be null or empty");

    JsonObject contentJson = new JsonObject();

    contentJson.addProperty("language", language == null ? LANGUAGE_EN : language);

    if (name != null && !name.isEmpty()) {
        contentJson.addProperty("name", name);
    }

    try {

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("training_data",
                new StringBody(TrainingDataUtils.toCSV(trainingData.toArray(new TrainingData[0]))));
        reqEntity.addPart("training_metadata", new StringBody(contentJson.toString()));

        HttpRequestBase request = Request.Post("/v1/classifiers").withEntity(reqEntity).build();
        HttpHost proxy = new HttpHost("10.100.1.124", 3128);
        ConnRouteParams.setDefaultProxy(request.getParams(), proxy);
        HttpResponse response = execute(request);
        return ResponseUtil.getObject(response, Classifier.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}