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.eclipse.egit.github.core.service.DownloadService.java

/**
 * Upload a resource to be available as the download described by the given
 * resource.//from   w w w  .  j  av  a 2 s. c om
 *
 * @param resource
 * @param content
 * @param size
 * @throws IOException
 */
public void uploadResource(DownloadResource resource, InputStream content, long size) throws IOException {
    if (resource == null)
        throw new IllegalArgumentException("Download resource cannot be null"); //$NON-NLS-1$
    if (content == null)
        throw new IllegalArgumentException("Content input stream cannot be null"); //$NON-NLS-1$

    HttpClient client = createDownloadClient();

    HttpPost post = new HttpPost(resource.getS3Url());
    MultipartEntity entity = new MultipartEntity();
    entity.addPart(UPLOAD_KEY, new StringBody(resource.getPath()));
    entity.addPart(UPLOAD_ACL, new StringBody(resource.getAcl()));
    entity.addPart(UPLOAD_SUCCESS_ACTION_STATUS, new StringBody(Integer.toString(HttpStatus.SC_CREATED)));
    entity.addPart(UPLOAD_FILENAME, new StringBody(resource.getName()));
    entity.addPart(UPLOAD_AWS_ACCESS_KEY_ID, new StringBody(resource.getAccesskeyid()));
    entity.addPart(UPLOAD_POLICY, new StringBody(resource.getPolicy()));
    entity.addPart(UPLOAD_SIGNATURE, new StringBody(resource.getSignature()));
    entity.addPart(HttpHeaders.CONTENT_TYPE, new StringBody(resource.getMimeType()));
    entity.addPart(UPLOAD_FILE, new SizedInputStreamBody(content, size));
    post.setEntity(entity);

    HttpResponse response = client.execute(post);
    int status = response.getStatusLine().getStatusCode();
    if (status != HttpStatus.SC_CREATED)
        throw new IOException("Unexpected response status of " + status); //$NON-NLS-1$
}

From source file:org.jboss.as.test.smoke.mgmt.servermodule.HttpGenericOperationUnitTestCase.java

private ContentBody getOperationBody(final ModelNode operation, final boolean encoded) throws IOException {
    if (encoded) {
        return new DMRContentEncodedBody(operation);
    } else {/*from w  ww . jav  a  2 s  .c  o m*/
        return new StringBody(operation.toJSONString(true));
    }
}

From source file:org.openbmap.soapclient.FileUploader.java

/**
 * @param file/*from   w  w  w .j av  a  2  s .c o m*/
 * @return
 */
private boolean performUpload(final String file) {
    // TODO check network state
    // @see http://developer.android.com/training/basics/network-ops/connecting.html

    // Adjust HttpClient parameters
    final HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used. 
    //HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    //HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT);
    final DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);

    final HttpPost httppost = new HttpPost(mServer);
    try {

        final String authorizationString = "Basic "
                + Base64.encodeToString((mUser + ":" + mPassword).getBytes(), Base64.NO_WRAP);
        httppost.setHeader("Authorization", authorizationString);

        final MultipartEntity entity = new MultipartEntity();

        // TODO we don't need passwords for the new service
        entity.addPart(LOGIN_FIELD, new StringBody(mUser));
        entity.addPart(PASSWORD_FIELD, new StringBody(mPassword));
        entity.addPart(FILE_FIELD, new FileBody(new File(file), "text/xml"));

        httppost.setEntity(entity);
        final HttpResponse response = httpclient.execute(httppost);

        final int reply = response.getStatusLine().getStatusCode();
        if (reply == 200) {
            Log.i(TAG, "Uploaded " + file + ": Server reply " + reply);
        } else {
            Log.w(TAG, "Error while uploading" + file + ": Server reply " + reply);
        }
        // everything is ok if we receive HTTP 200
        // TODO: redirects (301, 302) are NOT handled here 
        // thus if something changes on the server side we're dead here
        return (reply == HttpStatus.SC_OK);
    } catch (final ClientProtocolException e) {
        Log.e(TAG, e.getMessage());
    } catch (final IOException e) {
        Log.e(TAG, "I/O exception on file " + file);
    }
    return false;
}

From source file:org.deviceconnect.android.profile.restful.test.NormalFileDescriptorProfileTestCase.java

/**
 * ????./*from  w w w . ja v a2 s.c o  m*/
 * <pre>
 * ?HTTP
 * Method: PUT
 * Path: /file_descriptor/write?deviceid=xxxx&mediaid=xxxx
 * Entity: "test"
 * </pre>
 * <pre>
 * ??
 * result?0???????
 * </pre>
 */
public void testWrite001() {
    StringBuilder builder = new StringBuilder();
    builder.append(DCONNECT_MANAGER_URI);
    builder.append("/" + FileDescriptorProfileConstants.PROFILE_NAME);
    builder.append("/" + FileDescriptorProfileConstants.ATTRIBUTE_WRITE);
    builder.append("?");
    builder.append(DConnectProfileConstants.PARAM_DEVICE_ID + "=" + getDeviceId());
    builder.append("&");
    builder.append(FileDescriptorProfileConstants.PARAM_PATH + "=test.txt");
    builder.append("&");
    builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN + "=" + getAccessToken());
    try {
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("media", new StringBody("test"));
        HttpPut request = new HttpPut(builder.toString());
        request.addHeader("Content-Disposition", "form-data; name=\"media\"; filename=\"test.txt\"");
        request.setEntity(entity);
        JSONObject root = sendRequest(request);
        Assert.assertNotNull("root is null.", root);
        assertResultOK(root);
    } catch (JSONException e) {
        fail("Exception in JSONObject." + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        fail("Exception in StringBody." + e.getMessage());
    }
}

From source file:palamarchuk.smartlife.app.RegisterActivity.java

private MultipartEntity collectData() throws UnsupportedEncodingException {
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("email", new StringBody(email.getText().toString()));
    entity.addPart("password", new StringBody(password.getText().toString()));
    entity.addPart("first_name", new StringBody(name.getText().toString()));
    entity.addPart("birthdate", new StringBody(birthDateToServer));
    entity.addPart("gender", new StringBody(String.valueOf(gender)));
    entity.addPart("phone", new StringBody(phone.getText().toString()));
    entity.addPart("last_name", new StringBody(lastName.getText().toString()));
    entity.addPart("city_id", new StringBody(cities.getCityId()));
    entity.addPart("secret", new StringBody(registerActivitySecret.getText().toString()));
    entity.addPart("card_number", new StringBody(cardNumber));
    entity.addPart("pin", new StringBody(cardPinCode));
    return entity;
}

From source file:com.frentix.restapi.RestConnection.java

/**
 * Attach file to POST request./* www.jav a  2  s .  c om*/
 * 
 * @param post the request
 * @param filename the filename field
 * @param file the file
 * @throws UnsupportedEncodingException
 */
public void addMultipart(HttpEntityEnclosingRequestBase post, String filename, File file)
        throws UnsupportedEncodingException {

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("filename", new StringBody(filename));
    FileBody fileBody = new FileBody(file, "application/octet-stream");
    entity.addPart("file", fileBody);
    post.setEntity(entity);
}

From source file:org.fcrepo.integration.api.FedoraDatastreamsIT.java

License:asdf

@Test
public void testModifyMultipleDatastreams() throws Exception {
    final HttpPost objMethod = postObjMethod("FedoraDatastreamsTest8");

    assertEquals(201, getStatus(objMethod));

    final HttpPost createDSVOIDMethod = postDSMethod("FedoraDatastreamsTest8", "ds_void",
            "marbles for everyone");
    assertEquals(201, getStatus(createDSVOIDMethod));

    final HttpPost post = new HttpPost(
            serverAddress + "objects/FedoraDatastreamsTest8/datastreams?delete=ds_void");

    final MultipartEntity multiPartEntity = new MultipartEntity();
    multiPartEntity.addPart("ds1", new StringBody("asdfg"));
    multiPartEntity.addPart("ds2", new StringBody("qwerty"));

    post.setEntity(multiPartEntity);/*from   w  w w. ja v  a 2s . c o m*/

    final HttpResponse postResponse = client.execute(post);

    assertEquals(201, postResponse.getStatusLine().getStatusCode());

    final HttpGet getDSesMethod = new HttpGet(serverAddress + "objects/FedoraDatastreamsTest8/datastreams");
    final HttpResponse response = client.execute(getDSesMethod);
    assertEquals(200, response.getStatusLine().getStatusCode());
    final String content = EntityUtils.toString(response.getEntity());
    assertTrue("Didn't find the first datastream!", compile("dsid=\"ds1\"", DOTALL).matcher(content).find());
    assertTrue("Didn't find the second datastream!", compile("dsid=\"ds2\"", DOTALL).matcher(content).find());

    assertFalse("Found the deleted datastream!", compile("dsid=\"ds_void\"", DOTALL).matcher(content).find());

}

From source file:com.glasshack.checkmymath.CheckMyMath.java

public String post(String url, List<NameValuePair> nameValuePairs) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpPost httpPost = new HttpPost(url);
    String readableResponse = null;
    try {/*from w w w . jav  a 2  s  .c o  m*/
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        for (int index = 0; index < nameValuePairs.size(); index++) {
            if (nameValuePairs.get(index).getName().equalsIgnoreCase("file")) {
                // If the key equals to "file", we use FileBody to transfer the data
                entity.addPart("file",
                        new FileBody(new File(nameValuePairs.get(index).getValue()), "image/jpeg"));
            } else {
                // Normal string data
                entity.addPart(nameValuePairs.get(index).getName(),
                        new StringBody(nameValuePairs.get(index).getValue()));
            }
        }

        httpPost.setEntity(entity);

        HttpResponse response = httpClient.execute(httpPost, localContext);
        readableResponse = EntityUtils.toString(response.getEntity(), "UTF-8");

        Log.e("response", readableResponse);

    } catch (IOException e) {
        e.printStackTrace();
    }

    return readableResponse;
}

From source file:net.fluidnexus.FluidNexusAndroid.services.NexusServiceThread.java

/**
 * Start the listeners for zeroconf services
 *//*w  ww. j a  v  a  2s .  c  om*/
public void doStateNone() {
    if (wifiManager.getWifiState() == wifiManager.WIFI_STATE_ENABLED) {
        Cursor c = messagesProviderHelper.publicMessages();

        while (c.isAfterLast() == false) {
            String message_hash = c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_MESSAGE_HASH));
            boolean result = checkHash(message_hash);

            if (!result) {
                try {
                    JSONObject message = new JSONObject();
                    message.put("message_title",
                            c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_TITLE)));
                    message.put("message_content",
                            c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_CONTENT)));
                    message.put("message_hash",
                            c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_MESSAGE_HASH)));
                    message.put("message_type", c.getInt(c.getColumnIndex(MessagesProviderHelper.KEY_TYPE)));
                    message.put("message_time", c.getFloat(c.getColumnIndex(MessagesProviderHelper.KEY_TIME)));
                    message.put("message_received_time",
                            c.getFloat(c.getColumnIndex(MessagesProviderHelper.KEY_RECEIVED_TIME)));
                    message.put("message_priority",
                            c.getInt(c.getColumnIndex(MessagesProviderHelper.KEY_PRIORITY)));

                    String attachment_path = c
                            .getString(c.getColumnIndex(MessagesProviderHelper.KEY_ATTACHMENT_PATH));

                    //String serializedMessage = message.toString();

                    // First, get our nonce
                    consumer = new CommonsHttpOAuthConsumer(key, secret);
                    consumer.setTokenWithSecret(token, token_secret);
                    HttpPost nonce_request = new HttpPost(NEXUS_NONCE_URL);
                    consumer.sign(nonce_request);
                    HttpClient client = new DefaultHttpClient();
                    String response = client.execute(nonce_request, new BasicResponseHandler());
                    JSONObject object = new JSONObject(response);
                    String nonce = object.getString("nonce");

                    // Then, take our nonce and key and put them in the message
                    message.put("message_nonce", nonce);
                    message.put("message_key", key);

                    // Setup our multipart entity
                    MultipartEntity entity = new MultipartEntity();

                    // Deal with file attachment
                    if (!attachment_path.equals("")) {
                        File file = new File(attachment_path);
                        ContentBody cbFile = new FileBody(file);
                        entity.addPart("message_attachment", cbFile);

                        // add the original filename to the message
                        message.put("message_attachment_original_filename", c.getString(
                                c.getColumnIndex(MessagesProviderHelper.KEY_ATTACHMENT_ORIGINAL_FILENAME)));
                    }

                    String serializedMessage = message.toString();
                    ContentBody messageBody = new StringBody(serializedMessage);
                    entity.addPart("message", messageBody);

                    HttpPost message_request = new HttpPost(NEXUS_MESSAGE_URL);
                    message_request.setEntity(entity);

                    client = new DefaultHttpClient();
                    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

                    response = client.execute(message_request, new BasicResponseHandler());
                    object = new JSONObject(response);
                    boolean message_result = object.getBoolean("result");

                    if (message_result) {
                        ContentValues values = new ContentValues();
                        values.put(MessagesProviderHelper.KEY_MESSAGE_HASH, message_hash);
                        values.put(MessagesProviderHelper.KEY_UPLOADED, 1);
                        int res = messagesProviderHelper
                                .setPublic(c.getLong(c.getColumnIndex(MessagesProviderHelper.KEY_ID)), values);
                        if (res == 0) {
                            log.debug("Message with hash " + message_hash
                                    + " not found; this should never happen!");
                        }
                    }

                } catch (OAuthMessageSignerException e) {
                    log.debug("OAuthMessageSignerException: " + e);
                } catch (OAuthExpectationFailedException e) {
                    log.debug("OAuthExpectationFailedException: " + e);
                } catch (OAuthCommunicationException e) {
                    log.debug("OAuthCommunicationException: " + e);
                } catch (JSONException e) {
                    log.debug("JSON Error: " + e);
                } catch (IOException e) {
                    log.debug("IOException: " + e);
                }
            }
            c.moveToNext();
        }

        c.close();

    }

    setServiceState(STATE_SERVICE_WAIT);
}

From source file:com.google.cloud.solutions.smashpix.MainActivity.java

  /**
 * Uploads the image to Google Cloud Storage.
 *//*from www.  j  av a2  s . c  o  m*/
public Boolean uploadToCloudStorage(ServicesStorageSignedUrlResponse signedUrlParams,
  File localImageStoragePath){
  if (!signedUrlParams.isEmpty() && localImageStoragePath.exists())  {
    FileBody binary = new FileBody(localImageStoragePath);
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(signedUrlParams.getFormAction());
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    try {
      entity.addPart("bucket", new StringBody(signedUrlParams.getBucket()));
      entity.addPart("key", new StringBody(signedUrlParams.getFilename()));
      entity.addPart("policy", new StringBody(signedUrlParams.getPolicy()));
      entity.addPart("signature", new StringBody(signedUrlParams.getSignature()));
      entity.addPart("x-goog-meta-owner", new StringBody(accountName));
      entity.addPart("GoogleAccessId", new StringBody(signedUrlParams.getGoogleAccessId()));
      entity.addPart("file", binary);
    } catch (UnsupportedEncodingException e) {
      Log.e(Constants.APP_NAME, e.getMessage());
      return false;
    }

    httpPost.setEntity(entity);
    HttpResponse httpResponse;
    try {
      httpResponse = httpClient.execute(httpPost);
      if (httpResponse.getStatusLine().getStatusCode() == 204) {
        Log.i(Constants.APP_NAME, "Image Uploaded");
        return true;
      }
    } catch (ClientProtocolException e) {
        Log.e(Constants.APP_NAME, e.getMessage());
    } catch (IOException e) {
        Log.e(Constants.APP_NAME, e.getMessage());
    }
  }
  Log.e(Constants.APP_NAME, "Image Upload Failed");
  return false;
}