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, Charset charset) throws UnsupportedEncodingException 

Source Link

Usage

From source file:org.wisdom.test.http.MultipartBody.java

/**
 * Computes the request payload./*from   w w  w .  j  a  v a2 s  .co  m*/
 *
 * @return the payload containing the declared fields and files.
 */
public HttpEntity getEntity() {
    if (hasFile) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        for (Entry<String, Object> part : parameters.entrySet()) {
            if (part.getValue() instanceof File) {
                hasFile = true;
                builder.addPart(part.getKey(), new FileBody((File) part.getValue()));
            } else {
                builder.addPart(part.getKey(),
                        new StringBody(part.getValue().toString(), ContentType.APPLICATION_FORM_URLENCODED));
            }
        }
        return builder.build();
    } else {
        try {
            return new UrlEncodedFormEntity(getList(parameters), UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.ibuildapp.romanblack.TableReservationPlugin.utils.TableReservationHTTP.java

/**
 * This method sends HTTP request to add order.
 *
 * @param user//www. java 2s  . c om
 * @param handler
 * @param orderInfo
 * @return
 */
public static String sendAddOrderRequest(User user, Handler handler, TableReservationInfo orderInfo) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
    HttpConnectionParams.setSoTimeout(httpParameters, 15000);

    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpPost httppost = new HttpPost(ADD_ORDER_URL);
    Log.e(TAG, "ADD_ORDER_URL = " + ADD_ORDER_URL);

    MultipartEntity multipartEntity = new MultipartEntity();

    // user details
    String userType = null;
    String orderUUID = null;
    try {

        if (user.getAccountType() == User.ACCOUNT_TYPES.FACEBOOK) {
            userType = "facebook";
            multipartEntity.addPart("order_customer_name", new StringBody(
                    user.getUserFirstName() + " " + user.getUserLastName(), Charset.forName("UTF-8")));
        } else if (user.getAccountType() == User.ACCOUNT_TYPES.TWITTER) {
            userType = "twitter";
            multipartEntity.addPart("order_customer_name",
                    new StringBody(user.getUserName(), Charset.forName("UTF-8")));
        } else if (user.getAccountType() == User.ACCOUNT_TYPES.IBUILDAPP) {
            userType = "ibuildapp";
            multipartEntity.addPart("order_customer_name",
                    new StringBody(user.getUserName(), Charset.forName("UTF-8")));

        } else if (user.getAccountType() == User.ACCOUNT_TYPES.GUEST) {
            userType = "guest";
            multipartEntity.addPart("order_customer_name", new StringBody("Guest", Charset.forName("UTF-8")));
        }

        multipartEntity.addPart("user_type", new StringBody(userType, Charset.forName("UTF-8")));
        multipartEntity.addPart("user_id", new StringBody(user.getAccountId(), Charset.forName("UTF-8")));
        multipartEntity.addPart("app_id", new StringBody(orderInfo.getAppid(), Charset.forName("UTF-8")));
        multipartEntity.addPart("module_id", new StringBody(orderInfo.getModuleid(), Charset.forName("UTF-8")));

        // order UUID
        orderUUID = UUID.randomUUID().toString();
        multipartEntity.addPart("order_uid", new StringBody(orderUUID, Charset.forName("UTF-8")));

        // order details
        Date tempDate = orderInfo.getOrderDate();
        tempDate.setHours(orderInfo.getOrderTime().houres);
        tempDate.setMinutes(orderInfo.getOrderTime().minutes);
        tempDate.getTimezoneOffset();
        String timeZone = timeZoneToString();

        multipartEntity.addPart("time_zone", new StringBody(timeZone, Charset.forName("UTF-8")));
        multipartEntity.addPart("order_date_time",
                new StringBody(Long.toString(tempDate.getTime() / 1000), Charset.forName("UTF-8")));
        multipartEntity.addPart("order_persons",
                new StringBody(Integer.toString(orderInfo.getPersonsAmount()), Charset.forName("UTF-8")));
        multipartEntity.addPart("order_spec_request",
                new StringBody(orderInfo.getSpecialRequest(), Charset.forName("UTF-8")));
        multipartEntity.addPart("order_customer_phone",
                new StringBody(orderInfo.getPhoneNumber(), Charset.forName("UTF-8")));
        multipartEntity.addPart("order_customer_email",
                new StringBody(orderInfo.getCustomerEmail(), Charset.forName("UTF-8")));

        // add security part
        multipartEntity.addPart("app_id", new StringBody(Statics.appId, Charset.forName("UTF-8")));
        multipartEntity.addPart("token", new StringBody(Statics.appToken, Charset.forName("UTF-8")));

    } catch (Exception e) {
        Log.d("", "");
    }

    httppost.setEntity(multipartEntity);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    try {
        String strResponseSaveGoal = httpclient.execute(httppost, responseHandler);
        Log.d("sendAddOrderRequest", "");
        String res = JSONParser.parseQueryError(strResponseSaveGoal);

        if (res == null || res.length() == 0) {
            return orderUUID;
        } else {
            handler.sendEmptyMessage(ADD_REQUEST_ERROR);
            return null;
        }
    } catch (ConnectTimeoutException conEx) {
        handler.sendEmptyMessage(ADD_REQUEST_ERROR);
        return null;
    } catch (ClientProtocolException ex) {
        handler.sendEmptyMessage(ADD_REQUEST_ERROR);
        return null;
    } catch (IOException ex) {
        handler.sendEmptyMessage(ADD_REQUEST_ERROR);
        return null;
    }
}

From source file:nya.miku.wishmaster.http.ExtendedMultipartBuilder.java

/**
 *  ?   UTF-8/*from  w  ww.  j  av  a 2  s .c o  m*/
 * @param key ? ()
 * @param value ?
 * @return ? 
 */
public ExtendedMultipartBuilder addString(String key, String value) {
    return addPart(key, new StringBody(value, ContentType.create("text/plain", "UTF-8")));
}

From source file:com.sytecso.jbpm.client.rs.JbpmRestTemplate.java

private String requestPost(String url, Map<String, Object> parameters, boolean multipart) throws Exception {
    log.info("--- POST");
    MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
    if (parameters == null) {
        parameters = new HashMap<String, Object>();
    }/*from w w  w . j  a  v  a 2 s .c om*/
    Set<String> keys = parameters.keySet();
    for (String keyString : keys) {
        String value = parameters.get(keyString).toString();
        formparams.add(new BasicNameValuePair(keyString, value));
        if (multipart) {
            try {
                StringBody stringBody = new StringBody(value, Charset.forName("UTF-8"));
                //System.out.println(stringBody.);
                multiPartEntity.addPart(keyString, (ContentBody) stringBody);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    HttpPost httpPost = new HttpPost(url);
    if (multipart) {
        httpPost.setEntity(multiPartEntity);
    } else {
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");// new UrlEncodedFormEntity(formparams, "multipart/form-data");
        ////
        httpPost.setEntity(entity);
    }
    /*if(!this.SESSION_ID.equals("")){
    httpPost.setHeader("Cookie", "JSESSIONID="+SESSION_ID); 
    }*/
    HttpResponse response = httpClient.execute(httpPost);
    return read(response.getEntity().getContent());
}

From source file:jp.tonyu.soytext2.file.Comm.java

public Scriptable execMultiPart(String rootPath, String relPath, final Scriptable sparams, Object responseType)
        throws ClientProtocolException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(rootPath + relPath);
    final MultipartEntity reqEntity = new MultipartEntity();
    Scriptables.each(sparams, new StringPropAction() {

        @Override/*from  w w w. j  av  a2 s.  c o m*/
        public void run(String key, Object value) {
            if (value instanceof String) {
                String s = (String) value;
                try {
                    reqEntity.addPart(key, new StringBody(s, Charset.forName("UTF-8")));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else if (value instanceof Scriptable) {
                Scriptable s = (Scriptable) value;
                String filename = (String) ScriptableObject.getProperty(s, FileUpload.FILENAME);
                Object body = ScriptableObject.getProperty(s, FileUpload.BODY);
                InputStream st = null;
                if (body instanceof InputStream) {
                    st = (InputStream) body;
                } else if (body instanceof ReadableBinData) {
                    ReadableBinData rbd = (ReadableBinData) body;
                    try {
                        st = rbd.getInputStream();
                    } catch (IOException e) {
                        Log.die(e);
                    }
                }
                if (st == null)
                    throw new RuntimeException("Not a bindata - " + body);
                InputStreamBody bin = new InputStreamBody(st, filename);
                reqEntity.addPart(key, bin);
            }
        }
    });
    httppost.setEntity(reqEntity);

    Log.d(this, "executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    Scriptable res = response2Scriptable(response, responseType);
    return res;
}

From source file:io.undertow.servlet.test.charset.ParameterCharacterEncodingTestCase.java

@Test
public void testMultipartCharacterEncoding() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {/* w w w  . ja  v  a  2 s  .c o  m*/
        String message = "abc?";
        String charset = "UTF-8";

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/servletContext");

        MultipartEntity multipart = new MultipartEntity();
        multipart.addPart("charset", new StringBody(charset, Charset.forName(charset)));
        multipart.addPart("message", new StringBody(message, Charset.forName(charset)));
        post.setEntity(multipart);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals(message, response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.app.precared.utils.MultipartEntityBuilder.java

public MultipartEntityBuilder addTextBody(final String name, final String text, final ContentType contentType) {
    return addPart(name, new StringBody(text, contentType));
}

From source file:org.linkdroid.PostJob.java

/**
 * Posts the data to our webhook.//from  w ww. j a v  a  2 s  .co m
 * 
 * The HMAC field calculation notes:
 * <ol>
 * <li>The Extras.HMAC field is calculated from all the non Extras.STREAM
 * fields; this includes all the original bundle extra fields, plus the
 * linkdroid fields (e.g Extras.STREAM_MIME_TYPE, and including
 * Extras.STREAM_HMAC); the NONCE is NOT prepended to the input since it will
 * be somewhere in the data bundle.</li>
 * <li>The Extras.STREAM_HMAC field is calculated by digesting the concat of
 * the NONCE (first) and the actual binary data obtained from the
 * EXTRAS_STREAM uri; this STREAM_HMAC field (along with the other
 * Extras.STREAM_* fields) are added to the data bundle, which will also be
 * hmac'd.</li>
 * <li>If no hmac secret is set, then the NONCEs will not be set in the upload
 * </li>
 * </ol>
 * 
 * @param contentResolver
 * @param webhook
 * @param data
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws InvalidKeyException
 * @throws NoSuchAlgorithmException
 */
public static void execute(ContentResolver contentResolver, Bundle webhook, Bundle data)
        throws UnsupportedEncodingException, IOException, InvalidKeyException, NoSuchAlgorithmException {

    // Set constants that may be used in this method.
    final String secret = webhook.getString(WebhookColumns.SECRET);

    // This is the multipart form object that will contain all the data bundle
    // extras; it also will include the data of the extra stream and any other
    // extra linkdroid specific field required.
    MultipartEntity entity = new MultipartEntity();

    // Do the calculations to create our nonce string, if necessary.
    String nonce = obtainNonce(webhook);

    // Add the nonce to the data bundle if we have it.
    if (nonce != null) {
        data.putString(Extras.NONCE, nonce);
    }

    // We have a stream of data, so we need to add that to the multipart form
    // upload with a possible HMAC.
    if (data.containsKey(Intent.EXTRA_STREAM)) {
        Uri mediaUri = (Uri) data.get(Intent.EXTRA_STREAM);

        // Open our mediaUri, base 64 encode it and add it to our multipart upload
        // entity.
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Base64OutputStream b64os = new Base64OutputStream(baos);
        InputStream is = contentResolver.openInputStream(mediaUri);
        byte[] bytes = new byte[1024];
        int count;
        while ((count = is.read(bytes)) != -1) {
            b64os.write(bytes, 0, count);
        }
        is.close();
        baos.close();
        b64os.close();
        final String base64EncodedString = new String(baos.toByteArray(), UTF8);
        entity.addPart(Extras.STREAM, new StringBody(base64EncodedString, UTF8_CHARSET));

        // Add the mimetype of the stream to the data bundle.
        final String mimeType = contentResolver.getType(mediaUri);
        if (mimeType != null) {
            data.putString(Extras.STREAM_MIME_TYPE, mimeType);
        }

        // Do the hmac calculation of the stream and add it to the data bundle.
        // NOTE: This hmac string will be included as part of the input to the
        // other Extras hmac.
        if (shouldDoHmac(webhook)) {
            InputStream inputStream = contentResolver.openInputStream(mediaUri);
            final String streamHmac = hmacSha1(inputStream, secret, nonce);
            inputStream.close();
            data.putString(Extras.STREAM_HMAC, streamHmac);
            Log.d(TAG, "STREAM_HMAC: " + streamHmac);
        }
    }

    // Calculate the Hmac for all the items by iterating over the data bundle
    // keys in order.
    if (shouldDoHmac(webhook)) {
        final String dataHmac = calculateBundleExtrasHmac(data, secret);
        data.putString(Extras.HMAC, dataHmac);
        Log.d(TAG, "HMAC: " + dataHmac);
    }

    // Dump all the data bundle keys into the form.
    for (String k : data.keySet()) {
        Object value = data.get(k);
        // If the value is null, the key will still be in the form, but with
        // an empty string as its value.
        if (value != null) {
            entity.addPart(k, new StringBody(value.toString(), UTF8_CHARSET));
        } else {
            entity.addPart(k, new StringBody("", UTF8_CHARSET));
        }
    }

    // Create the client and request, then populate it with our multipart form
    // upload entity as part of the POST request; finally post the form.
    final String webhookUri = webhook.getString(WebhookColumns.URI);
    final HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(USER_AGENT_KEY, USER_AGENT);
    final HttpPost request = new HttpPost(webhookUri);
    request.setEntity(entity);
    HttpResponse response = client.execute(request);
    switch (response.getStatusLine().getStatusCode()) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
        break;
    default:
        throw new RuntimeException(response.getStatusLine().toString());
    }
}

From source file:org.dataconservancy.ui.it.support.MetadataFileRequest.java

public HttpPost asHttpPost() {

    String depositUrl = urlConfig.getMetadataFileUrl().toString();
    HttpPost post = new HttpPost(depositUrl);
    MultipartEntity entity = new MultipartEntity();
    try {//ww  w.ja v a2 s . c  om
        entity.addPart("parentID", new StringBody(parentId, Charset.forName("UTF-8")));
        if (name != null && !name.isEmpty()) {
            entity.addPart("metadataFile.name", new StringBody(name, Charset.forName("UTF-8")));
        }

        if (metadataFormat != null && !metadataFormat.isEmpty()) {
            entity.addPart("metadataFile.metadataFormatId",
                    new StringBody(metadataFormat, Charset.forName("UTF-8")));
        }

        if (id != null && !id.isEmpty()) {
            entity.addPart("metadataFileID", new StringBody(id, Charset.forName("UTF-8")));
        }

        if (isCollection) {
            entity.addPart("redirectUrl", new StringBody("viewCollectionDetails", Charset.forName("UTF-8")));
        }

        entity.addPart(event, new StringBody(event, Charset.forName("UTF-8")));

    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    if (fileToDeposit != null) {
        FileBody fileBody = new FileBody(fileToDeposit);
        entity.addPart("uploadedFile", fileBody);
        post.setEntity(entity);
    }
    return post;
}