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.craftercms.social.util.UGCHttpClient.java

private HttpPost manageAttachments(String[] attachments, String ticket, String target, String textContent)
        throws UnsupportedEncodingException, URISyntaxException {
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("ticket", ticket));
    URI uri = URIUtils.createURI(scheme, host, port, appPath + "/api/2/ugc/" + "create.json",
            URLEncodedUtils.format(qparams, HTTP.UTF_8), null);
    HttpPost httppost = new HttpPost(uri);

    if (attachments.length > 0) {

        MultipartEntity me = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        File file;//from  w  w w .j  ava2s .  c o  m
        FileBody fileBody;
        for (String f : attachments) {
            file = new File(f);
            fileBody = new FileBody(file, "application/octect-stream");
            me.addPart("attachments", fileBody);
        }
        //File file = new File(attachments[0]);
        //FileBody fileBody = new FileBody(file, "application/octect-stream") ;
        //me.addPart("attachments", fileBody) ;
        me.addPart("target", new StringBody(target));
        me.addPart("textContent", new StringBody(textContent));

        httppost.setEntity(me);
    }
    return httppost;
}

From source file:com.woonoz.proxy.servlet.HttpEntityEnclosingRequestHandler.java

private StringBody buildStringBody(FileItemStream fileItem) throws UnsupportedEncodingException, IOException {
    return new StringBody(IOUtils.toString(fileItem.openStream()));
}

From source file:net.asplode.tumblr.Post.java

/**
 * @param date//from w  ww .ja  v a 2  s.c  om
 *            Publish date and time for queued posts
 * @throws UnsupportedEncodingException
 */
public void setPublishOn(String date) throws UnsupportedEncodingException {
    entity.addPart("publish-on", new StringBody(date));
}

From source file:org.n52.oss.ui.controllers.ScriptController.java

@RequestMapping(method = RequestMethod.POST, value = "/upload")
public String processForm(@ModelAttribute(value = "uploadForm") uploadForm form, ModelMap map) {
    String s = form.getFile().getFileItem().getName();
    MultipartEntity multipartEntity = new MultipartEntity();
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();//  ww  w .  ja va  2s.c o  m
    String token = userDetails.getPassword();

    // upload the file
    File dest = new File(s);
    try {
        System.out.println("Chosen license:" + form.getLicense());
        log.info("Chosen license:" + form.getLicense());
        form.getFile().transferTo(dest);
        UserDetails details = (UserDetails) SecurityContextHolder.getContext().getAuthentication()
                .getPrincipal();
        multipartEntity.addPart("file", new FileBody(dest));
        multipartEntity.addPart("user", new StringBody(details.getUsername()));
        multipartEntity.addPart("licenseCode", new StringBody(form.getLicense()));
        multipartEntity.addPart("auth_token", new StringBody(token));
        HttpPost post = new HttpPost(OSSConstants.BASE_URL + "/OpenSensorSearch/script/submit");
        post.setEntity(multipartEntity);
        org.apache.http.client.HttpClient client = new DefaultHttpClient();
        HttpResponse resp;
        resp = client.execute(post);
        int responseCode = resp.getStatusLine().getStatusCode();
        StringBuilder builder = new StringBuilder();
        String str = null;
        BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        while ((str = reader.readLine()) != null)
            builder.append(str);
        System.out.println("return  id:" + builder.toString());
        log.info("return id:" + builder.toString());

        if (responseCode == 200) {
            map.addAttribute("harvestSuccess", true);
            map.addAttribute("resultScript", builder.toString());
            map.addAttribute("license", form.getLicense());
            return "script/status";
        } else {
            map.addAttribute("harvestError", true);
            return "script/status";
        }
    } catch (Exception e) {
        map.addAttribute("errorMSG", e);
        return "script/status?fail";
    }
}

From source file:com.ushahidi.android.app.net.CheckinHttpClient.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
 */// www  .j av  a  2  s  .co  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(params.get("task")));
            entity.addPart("action", new StringBody(params.get("action")));
            entity.addPart("mobileid", new StringBody(params.get("mobileid")));
            entity.addPart("message", new StringBody(params.get("message"), Charset.forName("UTF-8")));
            entity.addPart("lat", new StringBody(params.get("lat")));
            entity.addPart("lon", new StringBody(params.get("lon")));
            entity.addPart("firstname", new StringBody(params.get("firstname"), Charset.forName("UTF-8")));
            entity.addPart("lastname", new StringBody(params.get("lastname"), Charset.forName("UTF-8")));
            entity.addPart("email", new StringBody(params.get("email"), Charset.forName("UTF-8")));

            if (params.get("filename") != null) {
                if (!TextUtils.isEmpty(params.get("filename"))) {

                    File file = new File(ImageManager.getPhotoPath(context, params.get("filename")));

                    if (file != null) {
                        if (file.exists()) {

                            entity.addPart("photo", new FileBody(file));
                        }
                    }
                }
            }

            // 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.dmsl.anyplace.tasks.UploadRSSLogTask.java

@Override
protected String doInBackground(Void... params) {
    try {/* www  . ja va2  s .  c om*/
        JSONObject j;
        j = new JSONObject();
        j.put("username", username);
        j.put("password", password);
        String json = j.toString();

        File rsslog = new File(this.file);
        if (rsslog.exists() == false) {
            exceptionOccured = true;
            return "File not found";
        }
        Log.d("radio upload", rsslog.toString());
        String response;

        HttpClient httpclient = new DefaultHttpClient();
        httppost = new HttpPost(AnyplaceAPI.getRadioUploadUrl());

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("radiomap", new FileBody(rsslog));
        entity.addPart("json", new StringBody(json));

        ProgressCallback progressCallback = new ProgressCallback() {

            @Override
            public void progress(float progress) {
                if (currentProgress != (int) (progress)) {
                    currentProgress = (int) progress;
                    publishProgress(currentProgress);
                }
            }

        };

        httppost.setEntity(new ProgressHttpEntityWrapper(entity, progressCallback));
        HttpResponse httpresponse = httpclient.execute(httppost);
        HttpEntity resEntity = httpresponse.getEntity();

        response = EntityUtils.toString(resEntity);

        Log.d("radio upload", "response: " + response);

        j = new JSONObject(response);
        if (j.getString("status").equalsIgnoreCase("error")) {
            exceptionOccured = true;
            return "Error: " + j.getString("message");
        }

    } catch (JSONException e) {
        exceptionOccured = true;
        Log.d("upload rss log", e.getMessage());
        return "Cannot upload RSS log. JSONException occurred[ " + e.getMessage() + " ]";
    } catch (ParseException e) {
        exceptionOccured = true;
        Log.d("upload rss log", e.getMessage());
        return "Cannot upload RSS log. ParseException occurred[ " + e.getMessage() + " ]";
    } catch (IOException e) {
        exceptionOccured = true;
        Log.d("upload rss log", e.getMessage());

        if (httppost != null && httppost.isAborted()) {
            return "Uploading cancelled!";
        } else {
            return "Cannot upload RSS log. IOException occurred[ " + e.getMessage() + " ]";
        }

    }
    return "Successfully uploaded RSS log!";
}

From source file:net.asplode.tumblr.Post.java

/**
* @param date/*from w w w  .  j  av a  2s . c  o  m*/
*            The post date, if different from now, in the blog's timezone.
*            Most unambiguous formats are accepted, such as '2007-12-01
*            14:50:02'. Dates may not be in the future.
* @throws UnsupportedEncodingException
*/
public void setDate(String date) throws UnsupportedEncodingException {
    entity.addPart("date", new StringBody(date));
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitPicHelper.java

private TwitPicStatus uploadToTwitPic() {
    try {/*from ww w.j  a v a2  s .c om*/
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(POST_URL);
        post.addHeader("X-Auth-Service-Provider", SERVICE_PROVIDER);
        post.addHeader("X-Verify-Credentials-Authorization", getAuthrityHeader(twitter));

        if (file == null) {
            // only the input stream was sent, so we need to convert it to a file
            Log.v("talon_twitpic", "converting to file from input stream");
            String filePath = saveStreamTemp(stream);
            file = new File(filePath);
        } else {
            Log.v("talon_twitpic", "already have the file, going right to send it");
        }

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("key", new StringBody(TWITPIC_API_KEY));
        entity.addPart("media", new FileBody(file));
        entity.addPart("message", new StringBody(message));

        Log.v("talon_twitpic", "uploading now");

        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line;
        String url = "";
        StringBuilder builder = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            Log.v("talon_twitpic", line);
            builder.append(line);
        }

        try {
            // there is only going to be one thing returned ever
            JSONObject jsonObject = new JSONObject(builder.toString());
            url = jsonObject.getString("url");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.v("talon_twitpic", "url: " + url);
        Log.v("talon_twitpic", "message: " + message);

        return new TwitPicStatus(message, url);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.piusvelte.sonet.core.PhotoUploadService.java

private void start(Intent intent) {
    if (intent != null) {
        String action = intent.getAction();
        if (Sonet.ACTION_UPLOAD.equals(action)) {
            if (intent.hasExtra(Accounts.TOKEN) && intent.hasExtra(Statuses.MESSAGE)
                    && intent.hasExtra(Widgets.INSTANT_UPLOAD)) {
                String place = null;
                if (intent.hasExtra(Splace))
                    place = intent.getStringExtra(Splace);
                String tags = null;
                if (intent.hasExtra(Stags))
                    tags = intent.getStringExtra(Stags);
                // upload a photo
                Notification notification = new Notification(R.drawable.notification, "uploading photo",
                        System.currentTimeMillis());
                notification.setLatestEventInfo(getBaseContext(), "photo upload", "uploading",
                        PendingIntent.getActivity(PhotoUploadService.this, 0,
                                (Sonet.getPackageIntent(PhotoUploadService.this, About.class)), 0));
                ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFY_ID,
                        notification);// ww  w  .jav  a 2s .  c  o  m
                (new AsyncTask<String, Void, String>() {

                    @Override
                    protected String doInBackground(String... params) {
                        String response = null;
                        if (params.length > 2) {
                            Log.d(TAG, "upload file: " + params[2]);
                            HttpPost httpPost = new HttpPost(String.format(FACEBOOK_PHOTOS, FACEBOOK_BASE_URL,
                                    Saccess_token, mSonetCrypto.Decrypt(params[0])));
                            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                            File file = new File(params[2]);
                            ContentBody fileBody = new FileBody(file);
                            entity.addPart(Ssource, fileBody);
                            HttpClient httpClient = SonetHttpClient
                                    .getThreadSafeClient(getApplicationContext());
                            try {
                                entity.addPart(Smessage, new StringBody(params[1]));
                                if (params[3] != null)
                                    entity.addPart(Splace, new StringBody(params[3]));
                                if (params[4] != null)
                                    entity.addPart(Stags, new StringBody(params[4]));
                                httpPost.setEntity(entity);
                                response = SonetHttpClient.httpResponse(httpClient, httpPost);
                            } catch (UnsupportedEncodingException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                        return response;
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        // notify photo success
                        String message = getString(response != null ? R.string.success : R.string.failure);
                        Notification notification = new Notification(R.drawable.notification,
                                "photo upload " + message, System.currentTimeMillis());
                        notification.setLatestEventInfo(getBaseContext(), "photo upload", message,
                                PendingIntent.getActivity(PhotoUploadService.this, 0,
                                        (Sonet.getPackageIntent(PhotoUploadService.this, About.class)), 0));
                        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFY_ID,
                                notification);
                        stopSelfResult(mStartId);
                    }

                }).execute(intent.getStringExtra(Accounts.TOKEN), intent.getStringExtra(Statuses.MESSAGE),
                        intent.getStringExtra(Widgets.INSTANT_UPLOAD), place, tags);
            }
        }
    }
}

From source file:org.fedoraproject.eclipse.packager.bodhi.api.BodhiClient.java

@Override
public BodhiLoginResponse login(String username, String password) throws BodhiClientLoginException {
    BodhiLoginResponse result = null;//from w  ww  . ja v  a 2  s .  c om
    try {
        HttpPost post = new HttpPost(getLoginUrl());
        // Add "Accept: application/json" HTTP header
        post.addHeader(ACCEPT_HTTP_HEADER_NAME, MIME_JSON);

        // Construct the multipart POST request body.
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart(LOGIN_PARAM_NAME, new StringBody(LOGIN_PARAM_VALUE));
        reqEntity.addPart(USERNAME_PARAM_NAME, new StringBody(username));
        reqEntity.addPart(PASSWORD_PARAM_NAME, new StringBody(password));

        post.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(post);
        HttpEntity resEntity = response.getEntity();
        int returnCode = response.getStatusLine().getStatusCode();

        if (returnCode != HttpURLConnection.HTTP_OK) {
            throw new BodhiClientLoginException(NLS.bind("{0} {1}", response.getStatusLine().getStatusCode(), //$NON-NLS-1$
                    response.getStatusLine().getReasonPhrase()), response);
        } else {
            // Got a 200, response body is the JSON passed on from the
            // server.
            String jsonString = ""; //$NON-NLS-1$
            if (resEntity != null) {
                try {
                    jsonString = parseResponse(resEntity);
                } catch (IOException e) {
                    // ignore
                } finally {
                    EntityUtils.consume(resEntity); // clean up resources
                }
            }
            // log JSON string if in debug mode
            if (PackagerPlugin.inDebugMode()) {
                FedoraPackagerLogger logger = FedoraPackagerLogger.getInstance();
                logger.logInfo(NLS.bind(BodhiText.BodhiClient_rawJsonStringMsg, jsonString));
            }
            // Deserialize from JSON
            GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.registerTypeAdapter(DateTime.class, new DateTimeDeserializer());
            Gson gson = gsonBuilder.create();
            result = gson.fromJson(jsonString, BodhiLoginResponse.class);
        }
    } catch (IOException e) {
        throw new BodhiClientLoginException(e.getMessage(), e);
    }
    return result;
}