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:de.xwic.appkit.core.remote.client.MultipartRequestHelper.java

/**
 * @param entity/*from   ww  w . j a  v a2  s .  co  m*/
 * @param config
 * @throws UnsupportedEncodingException
 */
public MultipartRequestHelper(final MultipartEntity entity, final RemoteSystemConfiguration config)
        throws UnsupportedEncodingException {
    targetUrl = config.getRemoteBaseUrl() + config.getApiSuffix();
    entity.addPart(RemoteDataAccessServlet.PARAM_RSID, new StringBody(config.getRemoteSystemId()));

    IUser currentUser = DAOSystem.getSecurityManager().getCurrentUser();
    if (currentUser != null) {
        entity.addPart(RemoteDataAccessServlet.PARAM_USERNAME, new StringBody(currentUser.getLogonName()));
    }

    this.entity = entity;

}

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

/**
 * @param embed HTML to embed video or the URL of a YouTube video.
 * @throws UnsupportedEncodingException/*from www.j a v a  2s .  c om*/
 */
public void setEmbedText(String embed) throws UnsupportedEncodingException {
    entity.addPart("embed", new StringBody(embed));
}

From source file:com.willowtreeapps.uploader.testflight.TestFlightUploader.java

public Map upload(UploadRequest ur) throws IOException, org.json.simple.parser.ParseException {

    DefaultHttpClient httpClient = new DefaultHttpClient();

    HttpHost targetHost = new HttpHost(HOST);
    HttpPost httpPost = new HttpPost(POST);
    FileBody fileBody = new FileBody(ur.file);

    MultipartEntity entity = new MultipartEntity();
    entity.addPart("api_token", new StringBody(ur.apiToken));
    entity.addPart("team_token", new StringBody(ur.teamToken));
    entity.addPart("notes", new StringBody(ur.buildNotes));
    entity.addPart("file", fileBody);

    if (ur.dsymFile != null) {
        FileBody dsymFileBody = new FileBody(ur.dsymFile);
        entity.addPart("dsym", dsymFileBody);
    }//from   ww w  .  j a v a2  s. c o  m

    if (ur.lists.length() > 0) {
        entity.addPart("distribution_lists", new StringBody(ur.lists));
    }

    entity.addPart("notify", new StringBody(ur.notifyTeam ? "True" : "False"));
    entity.addPart("replace", new StringBody(ur.replace ? "True" : "False"));
    httpPost.setEntity(entity);

    return this.send(ur, httpClient, targetHost, httpPost);
}

From source file:hpcc.hut.edu.vn.ocr.ocrserviceconnector.HpccOcrServiceConnector.java

public static String postToOcrService(byte[] data, int size, int imgw, int imgh, String lang, int psm,
        boolean isPrePostProcess) {
    System.out.println("Sent data: w = " + imgw + ", h = " + imgh + ", psm = " + psm + ", process: "
            + isPrePostProcess + ", with lang: " + lang);
    String result = "";

    try {//from w w w.j a  v  a  2 s . co m
        HttpParams httpParamenters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParamenters, 30000);
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParamenters);
        HttpPost postRequest = new HttpPost(HOST);

        ByteArrayBody bab = new ByteArrayBody(data, "input.jpg");
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("image", bab);
        reqEntity.addPart("size", new StringBody("" + size)); // size to
        // check if
        // decompress
        // fail
        reqEntity.addPart("width", new StringBody("" + imgw));
        reqEntity.addPart("height", new StringBody("" + imgh));
        reqEntity.addPart("lang", new StringBody(lang));
        reqEntity.addPart("psm", new StringBody("" + psm));
        reqEntity.addPart("process", new StringBody("" + isPrePostProcess));

        postRequest.setEntity(reqEntity);

        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String sResponse;
        StringBuilder s = new StringBuilder();
        while ((sResponse = reader.readLine()) != null) {
            s = s.append(sResponse);
        }
        result = s.toString();
        System.out.println("result in Json: " + result);
    } catch (Exception e) {
        // handle exception here
        Log.e(e.getClass().getName(), e.getMessage());
        return null;
    }
    return result;

}

From source file:uk.ac.diamond.scisoft.feedback.FeedbackRequest.java

/**
 * Method used to submit a form data/file through HTTP to a GAE servlet
 * /*from  w  w w  . ja  v a  2s .  c o m*/
 * @param email
 * @param to
 * @param name
 * @param subject
 * @param messageBody
 * @param attachmentFiles
 * @param monitor
 */
public static IStatus doRequest(String email, String to, String name, String subject, String messageBody,
        List<File> attachmentFiles, IProgressMonitor monitor) throws Exception {
    Status status = null;
    DefaultHttpClient httpclient = new DefaultHttpClient();

    FeedbackProxy.init();
    host = FeedbackProxy.getHost();
    port = FeedbackProxy.getPort();

    if (monitor.isCanceled())
        return Status.CANCEL_STATUS;

    // if there is a proxy
    if (host != null) {
        HttpHost proxy = new HttpHost(host, port);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    if (monitor.isCanceled())
        return Status.CANCEL_STATUS;

    try {
        HttpPost httpost = new HttpPost(SERVLET_URL + SERVLET_NAME);

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("name", new StringBody(name));
        entity.addPart("email", new StringBody(email));
        entity.addPart("to", new StringBody(to));
        entity.addPart("subject", new StringBody(subject));
        entity.addPart("message", new StringBody(messageBody));

        // add attachement files to the multipart entity
        for (int i = 0; i < attachmentFiles.size(); i++) {
            if (attachmentFiles.get(i) != null && attachmentFiles.get(i).exists())
                entity.addPart("attachment" + i + ".html", new FileBody(attachmentFiles.get(i)));
        }

        if (monitor.isCanceled())
            return Status.CANCEL_STATUS;

        httpost.setEntity(entity);

        // HttpPost post = new HttpPost("http://dawnsci-feedback.appspot.com/dawnfeedback?name=baha&email=baha@email.com&subject=thisisasubject&message=thisisthemessage");
        HttpResponse response = httpclient.execute(httpost);

        if (monitor.isCanceled())
            return Status.CANCEL_STATUS;

        final String reasonPhrase = response.getStatusLine().getReasonPhrase();
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            logger.debug("Status code 200");
            status = new Status(IStatus.OK, "Feedback successfully sent", "Thank you for your contribution");
        } else {
            logger.debug("Feedback email not sent - HTTP response: " + reasonPhrase);
            status = new Status(IStatus.WARNING, "Feedback not sent",
                    "The response from the server is the following:\n" + reasonPhrase
                            + "\nClick on OK to submit your feedback using the online feedback form available at http://dawnsci-feedback.appspot.com/");
        }
        logger.debug("HTTP Response: " + response.getStatusLine());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
    return status;
}

From source file:com.qcloud.CloudClient.java

public String post(String url, Map<String, String> header, Map<String, Object> body, byte[] data)
        throws UnsupportedEncodingException, IOException {
    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("accept", "*/*");
    httpPost.setHeader("connection", "Keep-Alive");
    httpPost.setHeader("user-agent", "qcloud-java-sdk");
    if (header != null) {
        for (String key : header.keySet()) {
            httpPost.setHeader(key, header.get(key));
        }/*from  w  w  w  .j  a  v  a2  s  .  co m*/
    }

    if (false == header.containsKey("Content-Type")
            || header.get("Content-Type").equals("multipart/form-data")) {
        MultipartEntity multipartEntity = new MultipartEntity();
        if (body != null) {
            for (String key : body.keySet()) {
                multipartEntity.addPart(key, new StringBody(body.get(key).toString()));
            }
        }

        if (data != null) {
            ContentBody contentBody = new ByteArrayBody(data, "qcloud");
            multipartEntity.addPart("fileContent", contentBody);
        }
        httpPost.setEntity(multipartEntity);
    } else {
        if (data != null) {
            String strBody = new String(data);
            StringEntity stringEntity = new StringEntity(strBody);
            httpPost.setEntity(stringEntity);
        }
    }

    //        HttpHost proxy = new HttpHost("127.0.0.1",8888);
    //        mClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);

    HttpResponse httpResponse = mClient.execute(httpPost);
    int code = httpResponse.getStatusLine().getStatusCode();
    return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
}

From source file:org.opencastproject.remotetest.server.resource.IngestResources.java

/**
 * //from  ww w.  j ava 2  s. c  om
 * @param type
 *          Type of media to add: Track, Catalog, Attachment
 * 
 */
public static HttpResponse addTrack(TrustedHttpClient client, String type, InputStream media, String flavor,
        String mediaPackage) throws Exception {
    HttpPost post = new HttpPost(getServiceUrl() + "add" + type);
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("flavor", new StringBody(flavor));
    entity.addPart("mediaPackage", new StringBody(mediaPackage));
    post.setEntity(entity);
    return client.execute(post);
}

From source file:org.apache.sling.validation.testservices.ValidationServiceTest.java

@Test
public void testValidRequestModel1() throws IOException, JSONException {
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("sling:resourceType", new StringBody("validation/test/resourceType1"));
    entity.addPart("field1", new StringBody("HELLOWORLD"));
    entity.addPart("field2", new StringBody("30.01.1988"));
    entity.addPart(SlingPostConstants.RP_OPERATION, new StringBody("validation"));
    RequestExecutor re = getRequestExecutor().execute(
            getRequestBuilder().buildPostRequest("/validation/testing/fakeFolder1/resource").withEntity(entity))
            .assertStatus(200);// www.jav  a 2  s.  com
    JSONObject jsonResponse = new JSONObject(re.getContent());
    assertTrue(jsonResponse.getBoolean("valid"));
}

From source file:org.deviceconnect.android.manager.test.MultipartTest.java

/**
 * POST????????.//from  w ww  .j a v  a 2s  .  com
 */
public void testParsingMutilpartAsRequestParametersMethodPost() {
    URIBuilder builder = TestURIBuilder.createURIBuilder();
    builder.setProfile(NotificationProfileConstants.PROFILE_NAME);
    builder.setAttribute(NotificationProfileConstants.ATTRIBUTE_NOTIFY);
    try {
        MultipartEntity entity = new MultipartEntity();
        entity.addPart(DConnectProfileConstants.PARAM_DEVICE_ID, new StringBody(getDeviceId()));
        entity.addPart(NotificationProfileConstants.PARAM_TYPE, new StringBody("0"));
        entity.addPart(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN, new StringBody(getAccessToken()));
        HttpPost request = new HttpPost(builder.toString());
        request.setEntity(entity);
        JSONObject response = sendRequest(request);
        assertResultOK(response);
    } catch (UnsupportedEncodingException e) {
        fail(e.getMessage());
    } catch (JSONException e) {
        fail(e.getMessage());
    }
}

From source file:com.gorillalogic.monkeytalk.server.tests.MultipartTest.java

@Test
public void testMultipart() throws IOException, JSONException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:" + PORT + "/");

    File image = new File("resources/test/base.png");
    FileBody imagePart = new FileBody(image);
    StringBody messagePart = new StringBody("some message");

    MultipartEntity req = new MultipartEntity();
    req.addPart("image", imagePart);
    req.addPart("message", messagePart);
    httppost.setEntity(req);//  w ww .  j  av  a2  s  . co  m

    ImageEchoServer server = new ImageEchoServer(PORT);
    HttpResponse response = httpclient.execute(httppost);
    server.stop();

    HttpEntity resp = response.getEntity();
    assertThat(resp.getContentType().getValue(), is("application/json"));

    // sweet one-liner to convert an inputstream to a string from stackoverflow:
    // http://stackoverflow.com/questions/309424/in-java-how-do-i-read-convert-an-inputstream-to-a-string
    String out = new Scanner(resp.getContent()).useDelimiter("\\A").next();

    JSONObject json = new JSONObject(out);

    String base64 = Base64.encodeFromFile("resources/test/base.png");

    assertThat(json.getString("screenshot"), is(base64));
    assertThat(json.getBoolean("imageEcho"), is(true));
}