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

Source Link

Usage

From source file:org.witness.ssc.xfer.utils.PublishingUtils.java

public Thread videoUploadToVideoBin(final Activity activity, final Handler handler,
        final String video_absolutepath, final String title, final String description,
        final String emailAddress, final long sdrecord_id) {

    Log.d(TAG, "doPOSTtoVideoBin starting");

    // Make the progress bar view visible.
    ((SSCXferActivity) activity).startedUploading();
    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.

            boolean failed = false;

            HttpClient client = new DefaultHttpClient();

            if (useProxy) {
                HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT_HTTP);
                client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            }/*from w  w  w  .  jav  a  2s . co  m*/

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

            URI url = null;
            try {
                url = new URI(res.getString(R.string.http_videobin_org_add));
            } catch (URISyntaxException e) {
                // Ours is a fixed URL, so not likely to get here.
                e.printStackTrace();
                return;

            }
            HttpPost post = new HttpPost(url);
            CustomMultiPartEntity entity = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                    new ProgressListener() {
                        int lastPercent = 0;

                        @Override
                        public void transferred(long num) {

                            percentUploaded = (int) (((float) num) / ((float) totalLength) * 99f);
                            //Log.d(TAG, "percent uploaded: " + percentUploaded + " - " + num + " / " + totalLength);
                            if (lastPercent != percentUploaded) {
                                ((SSCXferActivity) activity).showProgress("uploading...", percentUploaded);
                                lastPercent = percentUploaded;
                            }
                        }

                    });

            File file = new File(video_absolutepath);
            entity.addPart(res.getString(R.string.video_bin_API_videofile), new FileBody(file));

            try {
                entity.addPart(res.getString(R.string.video_bin_API_api),
                        new StringBody("1", "text/plain", Charset.forName("UTF-8")));

                // title
                entity.addPart(res.getString(R.string.video_bin_API_title),
                        new StringBody(title, "text/plain", Charset.forName("UTF-8")));

                // description
                entity.addPart(res.getString(R.string.video_bin_API_description),
                        new StringBody(description, "text/plain", Charset.forName("UTF-8")));

            } catch (IllegalCharsetNameException e) {
                // error
                e.printStackTrace();
                failed = true;

            } catch (UnsupportedCharsetException e) {
                // error
                e.printStackTrace();
                return;
            } catch (UnsupportedEncodingException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            post.setEntity(entity);

            totalLength = entity.getContentLength();

            // Here we go!
            String response = null;
            try {
                response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
            } catch (ParseException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (ClientProtocolException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (IOException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            client.getConnectionManager().shutdown();

            if (failed) {
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((SSCXferActivity) activity).finishedUploading(false);

                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_videobin_org_failed_));
                    }
                }, 0);

                return;
            }

            Log.d(TAG, " video bin got back " + response);

            // XXX Convert to preference for auto-email on videobin post
            // XXX ADD EMAIL NOTIF to all other upload methods
            // stuck on YES here, if email is defined.

            if (emailAddress != null && response != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + response, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

            // Log record of this URL in POSTs table
            dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id,
                    res.getString(R.string.http_videobin_org_add), response, "");

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((SSCXferActivity) activity).finishedUploading(true);
                    ((SSCXferActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_videobin_org_succeeded_));

                }
            }, 0);
        }
    });

    t.start();

    return t;

}

From source file:ecblast.test.EcblastTest.java

public String executeCompareReactions(File queryFile, File targetFile) {
    String urlString = "http://localhost:8080/ecblast-rest/compare";
    DefaultHttpClient client;//from  w w  w  .j a v a 2 s .co  m
    client = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(urlString);

    try {
        //Set various attributes
        MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        FileBody queryFileBody = new FileBody(queryFile);
        //Prepare payload
        multiPartEntity.addPart("q", queryFileBody);
        multiPartEntity.addPart("Q", new StringBody("RXN", "text/plain", Charset.forName("UTF-8")));

        FileBody targetFileBody = new FileBody(targetFile);
        multiPartEntity.addPart("t", targetFileBody);
        multiPartEntity.addPart("T", new StringBody("RXN", "text/plain", Charset.forName("UTF-8")));
        //Set to request body
        postRequest.setEntity(multiPartEntity);

        //Send request
        HttpResponse response = client.execute(postRequest);

        //Verify response if any
        if (response != null) {
            System.out.println(response.getStatusLine().getStatusCode());

            return response.toString();
        }
    } catch (IOException ex) {
        return null;
    }
    return null;

}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.services.AuthClientService.java

public boolean createUser(String accountId, UserCreate user, String contentPath)
        throws TransportException, InvalidDataException, NotFoundException, KurentoCommandException {
    log.debug("Create user {}", user.getName());
    JSONObject object = new JSONObject();
    try {// ww w.j  av  a 2s.co m
        object.put(JsonKeys.PASSWORD, user.getPassword());
        object.put(JsonKeys.NAME, user.getName());
        object.put(JsonKeys.SURNAME, user.getSurname());
        object.put(JsonKeys.PHONE, user.getPhone());
        object.put(JsonKeys.EMAIL, user.getEmail());
        object.put(JsonKeys.PHONE_REGION, ConstantKeys.ES);

    } catch (JSONException e) {
        log.debug("Error creating object");
        return false;
    }
    String json = object.toString();

    String charset = HTTP.UTF_8;

    MultipartEntity mpEntity = new MultipartEntity();
    try {
        mpEntity.addPart(USER_PART_NAME,
                new StringBody(json, HttpManager.CONTENT_TYPE_APPLICATION_JSON, Charset.forName(charset)));
    } catch (UnsupportedEncodingException e) {
        String msg = "Cannot use " + charset + "as entity";
        log.error(msg, e);
        throw new TransportException(msg);
    }

    File content = new File(contentPath);
    mpEntity.addPart(PICTURE_PART_NAME, new FileBody(content, ConstantKeys.TYPE_IMAGE));

    HttpResp<Void> resp = HttpManager.sendPostVoid(context,
            context.getString(R.string.url_create_user, accountId), mpEntity);

    return resp.getCode() == HttpStatus.SC_CREATED;
}

From source file:io.undertow.servlet.test.multipart.MultiPartTestCase.java

@Test
public void testMultiPartIndividualFileToLarge() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {/*ww w. j a v a 2s.c  o m*/
        String uri = DefaultServer.getDefaultServerURL() + "/servletContext/3";
        HttpPost post = new HttpPost(uri);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file",
                new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("TEST FAILED: wrong response code\n" + response, StatusCodes.INTERNAL_SERVER_ERROR,
                result.getStatusLine().getStatusCode());
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:ecblast.test.EcblastTest.java

public String compareReactions(String queryFormat, String query, String targetFormat, String target)
        throws Exception {
    DefaultHttpClient client;//from   w  w w. j ava2 s  .  c o m
    client = new DefaultHttpClient();
    String urlString = "http://localhost:8080/ecblast-rest/compare";
    HttpPost postRequest = new HttpPost(urlString);
    try {
        //Set various attributes
        MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        //multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : ""));
        //multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName()));
        switch (queryFormat) {
        case "RXN":
            FileBody fileBody = new FileBody(new File(query));
            //Prepare payload
            multiPartEntity.addPart("q", fileBody);
            multiPartEntity.addPart("Q", new StringBody("RXN", "text/plain", Charset.forName("UTF-8")));
            break;
        case "SMI":
            multiPartEntity.addPart("q", new StringBody(query, "text/plain", Charset.forName("UTF-8")));
            multiPartEntity.addPart("Q", new StringBody("SMI", "text/plain", Charset.forName("UTF-8")));
            break;
        }
        switch (targetFormat) {
        case "RXN":
            FileBody fileBody = new FileBody(new File(target));
            //Prepare payload
            multiPartEntity.addPart("t", fileBody);
            multiPartEntity.addPart("T", new StringBody("RXN", "text/plain", Charset.forName("UTF-8")));
            break;
        case "SMI":
            multiPartEntity.addPart("t", new StringBody(target, "text/plain", Charset.forName("UTF-8")));
            multiPartEntity.addPart("T", new StringBody("SMI", "text/plain", Charset.forName("UTF-8")));
            break;
        }

        //Set to request body
        postRequest.setEntity(multiPartEntity);

        //Send request
        HttpResponse response = client.execute(postRequest);

        //Verify response if any
        if (response != null) {
            System.out.println(response.getStatusLine().getStatusCode());
            return response.toString();
        }
    } catch (IOException ex) {
    }
    return null;
}

From source file:org.trancecode.xproc.step.RequestParser.java

private FormBodyPart getContentBody(final XdmNode node, final Processor processor) {
    final String contentTypeAtt = node.getAttributeValue(XProcXmlModel.Attributes.CONTENT_TYPE);
    final String encoding = node.getAttributeValue(XProcXmlModel.Attributes.ENCODING);
    final ContentType contentType = Steps.getContentType(contentTypeAtt, node);
    final String contentString = getContentString(node, contentType, encoding, processor);
    final StringBody body;
    try {//from  ww w .jav  a 2s  .  com
        body = new StringBody(contentString, contentType.toString(),
                Steps.getCharset(contentType.getParameter("charset")));
    } catch (final UnsupportedEncodingException e) {
        throw XProcExceptions.xc0020(node);
    }

    final String id = node.getAttributeValue(XProcXmlModel.Attributes.ID);
    final String description = node.getAttributeValue(XProcXmlModel.Attributes.DESCRIPTION);
    final String disposition = node.getAttributeValue(XProcXmlModel.Attributes.DISPOSITION);
    final FormBodyPart bodyPart = new FormBodyPart("body", body) {
        @Override
        protected void generateContentDisp(final ContentBody body) {
            if (disposition != null) {
                addField(MIME.CONTENT_DISPOSITION, disposition);
            }
        }

        @Override
        protected void generateTransferEncoding(final ContentBody body) {
            if (encoding != null) {
                addField(MIME.CONTENT_TRANSFER_ENC, encoding);
            }
        }

        @Override
        protected void generateContentType(final ContentBody body) {
            final StringBuilder buffer = new StringBuilder();
            buffer.append(body.getMimeType());
            if (body.getCharset() != null) {
                try {
                    final String testCharset = new ContentType(body.getMimeType()).getParameter("charset");
                    if (testCharset != null) {
                        final Charset charset = Charset.forName(testCharset);
                        if (!StringUtils.equalsIgnoreCase(charset.displayName(), body.getCharset())) {
                            buffer.append("; charset=").append(body.getCharset().toLowerCase());
                        }
                    } else {
                        buffer.append("; charset=utf-8");
                    }
                } catch (final ParseException | IllegalCharsetNameException e) {
                    throw XProcExceptions.xc0020(node);
                }
            }
            addField(MIME.CONTENT_TYPE, buffer.toString());
        }
    };
    if (id != null) {
        bodyPart.addField("Content-ID", id);
    }
    if (description != null) {
        bodyPart.addField("Content-Description", description);
    }

    return bodyPart;
}

From source file:com.soundcloud.playerapi.Request.java

/**
 * Builds a request with the given set of parameters and files.
 * @param method    the type of request to use
 * @param <T>       the type of request to use
 * @return HTTP request, prepared to be executed
 *///from  w w  w  . j a  va 2  s  .c om
public <T extends HttpRequestBase> T buildRequest(Class<T> method) {
    try {
        T request = method.newInstance();
        // POST/PUT ?
        if (request instanceof HttpEntityEnclosingRequestBase) {
            HttpEntityEnclosingRequestBase enclosingRequest = (HttpEntityEnclosingRequestBase) request;

            final Charset charSet = java.nio.charset.Charset.forName(UTF_8);
            if (isMultipart()) {
                MultipartEntity multiPart = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, // XXX change this to STRICT once rack on server is upgraded
                        null, charSet);

                if (mFiles != null) {
                    for (Map.Entry<String, Attachment> e : mFiles.entrySet()) {
                        multiPart.addPart(e.getKey(), e.getValue().toContentBody());
                    }
                }

                for (NameValuePair pair : mParams) {
                    multiPart.addPart(pair.getName(), new StringBody(pair.getValue(), "text/plain", charSet));
                }

                enclosingRequest.setEntity(
                        listener == null ? multiPart : new CountingMultipartEntity(multiPart, listener));

                request.setURI(URI.create(mResource));

                // form-urlencoded?
            } else if (mEntity != null) {
                request.setHeader(mEntity.getContentType());
                enclosingRequest.setEntity(mEntity);
                request.setURI(URI.create(toUrl())); // include the params

            } else {
                if (!mParams.isEmpty()) {
                    request.setHeader("Content-Type", "application/x-www-form-urlencoded");
                    enclosingRequest.setEntity(new StringEntity(queryString()));
                }
                request.setURI(URI.create(mResource));
            }

        } else { // just plain GET/HEAD/DELETE/...
            if (mRange != null) {
                request.addHeader("Range", formatRange(mRange));
            }

            if (mIfNoneMatch != null) {
                request.addHeader("If-None-Match", mIfNoneMatch);
            }
            request.setURI(URI.create(toUrl()));
        }

        if (mToken != null) {
            request.addHeader(ApiWrapper.createOAuthHeader(mToken));
        }
        return request;
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.camel.component.cxf.jaxrs.simplebinding.CxfRsConsumerSimpleBindingTest.java

@Test
public void testMultipartPostWithParametersAndPayload() throws Exception {
    HttpPost post = new HttpPost(
            "http://localhost:" + PORT_PATH + "/rest/customerservice/customers/multipart/123?query=abcd");
    MultipartEntity multipart = new MultipartEntity(HttpMultipartMode.STRICT);
    multipart.addPart("part1", new FileBody(
            new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), "java.jpg"));
    multipart.addPart("part2", new FileBody(
            new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), "java.jpg"));
    StringWriter sw = new StringWriter();
    jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw);
    multipart.addPart("body", new StringBody(sw.toString(), "text/xml", Charset.forName("UTF-8")));
    post.setEntity(multipart);/*from  ww w .  jav a  2s  .  co  m*/
    HttpResponse response = httpclient.execute(post);
    assertEquals(200, response.getStatusLine().getStatusCode());
}

From source file:org.jkan997.slingbeans.slingfs.FileSystemServer.java

public byte[] sendPost(String url, Map<String, Object> changes, Map<String, Object> otherParams) {
    if ((!url.startsWith("http://")) && (!url.startsWith("https://"))) {
        url = serverPrefix + (!url.startsWith("/") ? "/" : "") + url;
    }/*from ww  w  . j a  va 2 s.co m*/
    if (((changes == null) || (changes.isEmpty())) && ((otherParams == null) || (otherParams.isEmpty()))) {
        return null;
    }
    try {
        httpClient = getHttpClient();
        LogHelper.logInfo(this, url);
        StringBuilder diff = new StringBuilder();
        HttpPost post = new HttpPost(url);
        configureAuth(post);
        MultipartEntity reqEntity = new MultipartEntity(null, "slingfs", UTF_8);
        Set<String> skipVals = new TreeSet<String>();
        if ((changes != null) && (!changes.isEmpty())) {
            boolean first = true;
            for (Map.Entry<String, Object> me : changes.entrySet()) {
                String val = ObjectHelper.toString(me.getValue(), "");
                String key = me.getKey();
                if (first) {
                    first = false;
                } else {
                    diff.append("\r\n");
                }
                if (key.startsWith("-")) {
                    skipVals.add(key);
                    diff.append(key + " : " + val);
                } else if (key.startsWith("+")) {
                    diff.append(key + " : \"xxx\"");
                    //skipVals.add(key);
                } else {
                    diff.append("^/" + key + " : ");
                }
            }
            reqEntity.addPart(":diff", new StringBody(diff.toString(), TEXT_PLAIN, UTF_8));
            for (Map.Entry<String, Object> me : changes.entrySet()) {
                String key = me.getKey();
                if (!skipVals.contains(key)) {
                    if ((key.startsWith("^/")) || (key.startsWith("+/"))) {
                        key = key.substring(2);
                    }
                    String jcrPath = "/" + key;
                    reqEntity.addPart(jcrPath, generateBody(me.getKey(), me.getValue()));
                }
            }
        }
        if ((otherParams != null) && (!otherParams.isEmpty())) {
            for (Map.Entry<String, Object> me : otherParams.entrySet()) {
                reqEntity.addPart(me.getKey(), generateBody(me.getKey(), me.getValue()));
            }
        }
        post.setEntity(reqEntity);
        long timeStamp = System.currentTimeMillis();
        dumpHttpRequest(reqEntity, timeStamp);
        HttpResponse response = httpClient.execute(post);
        HttpEntity resEntity = response.getEntity();
        byte[] res = getResponseBytes(resEntity, timeStamp);
        post.releaseConnection();
        return res;
    } catch (Exception ex) {
        LogHelper.logError(ex);
    }
    return null;
}

From source file:org.apache.camel.component.cxf.jaxrs.simplebinding.CxfRsConsumerSimpleBindingTest.java

@Test
public void testMultipartPostWithoutParameters() throws Exception {
    HttpPost post = new HttpPost("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/multipart");
    MultipartEntity multipart = new MultipartEntity(HttpMultipartMode.STRICT);
    multipart.addPart("part1", new FileBody(
            new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), "java.jpg"));
    multipart.addPart("part2", new FileBody(
            new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), "java.jpg"));
    StringWriter sw = new StringWriter();
    jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw);
    multipart.addPart("body", new StringBody(sw.toString(), "text/xml", Charset.forName("UTF-8")));
    post.setEntity(multipart);/*from   w w w  . j a va2  s  .  c om*/
    HttpResponse response = httpclient.execute(post);
    assertEquals(200, response.getStatusLine().getStatusCode());
}