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.file.impl.hbn.RemoteFileAccessClient.java

@Override
protected int storeFile(final File file) throws IOException {
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
    multipartEntity.addPart(PARAM_ACTION, new StringBody(ACTION_FILE_HANDLE));
    multipartEntity.addPart(PARAM_FH_ACTION, new StringBody(PARAM_FH_ACTION_UPLOAD));
    multipartEntity.addPart(PARAM_FH_STREAM, new FileBody(file));
    return URemoteAccessClient.multipartRequestInt(multipartEntity, config);
}

From source file:org.apache.felix.webconsole.plugins.scriptconsole.integration.ITScriptConsolePlugin.java

private void execute(ContentBody code) throws Exception {
    RequestBuilder rb = new RequestBuilder(ServerConfiguration.getServerUrl());

    final MultipartEntity entity = new MultipartEntity();
    // Add Sling POST options
    entity.addPart("lang", new StringBody("groovy"));
    entity.addPart("code", code);
    executor.execute(/*from  w  w w  .j  a v  a  2  s  .  c o  m*/
            rb.buildPostRequest("/system/console/sc").withEntity(entity).withCredentials("admin", "admin"))
            .assertStatus(200);
}

From source file:org.apache.sling.testing.tools.osgi.WebconsoleClient.java

public void uninstallBundle(String symbolicName, File f) throws Exception {
    final long bundleId = getBundleId(symbolicName);

    log.info("Uninstalling bundle {} with bundleId {}", symbolicName, bundleId);

    final MultipartEntity entity = new MultipartEntity();
    entity.addPart("action", new StringBody("uninstall"));
    executor.execute(builder.buildPostRequest(CONSOLE_BUNDLES_PATH + "/" + bundleId)
            .withCredentials(username, password).withEntity(entity)).assertStatus(200);
}

From source file:net.ccghe.emocha.async.UploadOneFile.java

public UploadOneFile(String path, String serverURL, FileTransmitter transmitter, MultipartEntity postData) {
    // configure connection
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 20 * Constants.ONE_SECOND);
    HttpConnectionParams.setSoTimeout(params, 20 * Constants.ONE_SECOND);
    HttpClientParams.setRedirecting(params, false);

    // setup client
    DefaultHttpClient client = new DefaultHttpClient(params);

    HttpPost post = new HttpPost(serverURL);

    int id = 0;/* w ww  . jav a2  s. c om*/
    postData.addPart("file" + id, new FileBody(new File(path)));
    try {
        postData.addPart("path" + id, new StringBody(path));
    } catch (UnsupportedEncodingException e1) {
        Log.e(Constants.LOG_TAG, "Encoding error while uploading file.");
    }

    // prepare response and return uploaded
    try {
        post.setEntity(postData);
        HttpResponse response = client.execute(post);

        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        String jsonResponse = Server.convertStreamToString(stream);
        stream.close();
        if (postData != null) {
            postData.consumeContent();
        }
        JSONObject jObject = new JSONObject(jsonResponse);

        Long ok = jObject.getLong("ok");

        if (ok > 0) {
            DBAdapter.markAsUploaded(path);
            Log.i(Constants.LOG_TAG, "Mark as uploaded: " + path);
        } else {
            Log.e(Constants.LOG_TAG, "Error uploading: " + path + " (json response not ok)");
        }
    } catch (ClientProtocolException e) {
        Log.e("EMOCHA", "ClientProtocolException ERR. " + e.getMessage());
    } catch (IOException e) {
        Log.e("EMOCHA", "IOException ERR. " + e.getMessage());
    } catch (Exception e) {
        Log.e("EMOCHA", "Exception ERR. " + e.getMessage());
    }

    /*
    // check response.
    // TODO: This isn't handled correctly.
    String serverLocation = null;
    Header[] h = response.getHeaders("Location");
    if (h != null && h.length > 0) {
       serverLocation = h[0].getValue();
    } else {
       // something should be done here...
       Log.e(Constants.LOG_TAG, "Location header was absent");
    }
    int responseCode = response.getStatusLine().getStatusCode();
    Log.e(Constants.LOG_TAG, "Response code:" + responseCode);
            
    // verify that your response came from a known server
    if (serverLocation != null && serverURL.contains(serverLocation)
    && responseCode == 201) {
       DBAdapter.markAsUploaded(path);
    }
    */
    transmitter.transmitComplete();
}

From source file:org.jcommon.com.facebook.utils.FacebookRequest.java

public void run() {
    HttpClient httpclient = new DefaultHttpClient();
    try {/*w  ww . j a  va  2s. c om*/
        logger.info(Integer.valueOf("file size:" + this.in != null ? this.in.available() : 0));
        HttpPost httppost = new HttpPost(this.url_);
        MultipartEntity reqEntity = new MultipartEntity();

        FormBodyPart stream_part = new FormBodyPart(this.stream_name,
                new InputStreamBody(this.in, this.file_name));

        reqEntity.addPart(stream_part);
        for (int i = 0; i < this.keys.length; i++) {
            reqEntity.addPart(this.keys[i], new StringBody(this.values[i]));
        }

        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        StatusLine status_line = response.getStatusLine();
        int responseCode = status_line.getStatusCode();

        BufferedReader http_reader = null;
        if (responseCode == 200) {
            http_reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), "utf-8"));
            String line = null;
            while ((line = http_reader.readLine()) != null) {
                this.sResult.append(line);
            }
            if (this.listener_ != null)
                this.listener_.onSuccessful(this, this.sResult);
        } else if (responseCode >= 400) {
            http_reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), "utf-8"));
            String line = null;
            while ((line = http_reader.readLine()) != null) {
                this.sResult.append(line);
            }
            logger.info("[URL][response][failure]" + this.sResult);
            if (this.listener_ != null)
                this.listener_.onFailure(this, this.sResult);
        } else {
            this.sResult.append("[URL][response][failure][code : " + responseCode + " ]");
            if (this.listener_ != null)
                this.listener_.onFailure(this, this.sResult);
            logger.info("[URL][response][failure][code : " + responseCode + " ]");
        }
        EntityUtils.consume(resEntity);
    } catch (UnsupportedEncodingException e) {
        logger.warn("[HttpReqeust] error:" + this.url_ + "\n" + e);
        if (this.listener_ != null)
            this.listener_.onException(this, e);
    } catch (ClientProtocolException e) {
        logger.warn("[HttpReqeust] error:" + this.url_ + "\n" + e);
        if (this.listener_ != null)
            this.listener_.onException(this, e);
    } catch (IOException e) {
        logger.warn("[HttpReqeust] error:" + this.url_ + "\n" + e);
        if (this.listener_ != null)
            this.listener_.onException(this, e);
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
        }
    }
}

From source file:fr.ippon.wip.http.request.MultipartRequestBuilder.java

public HttpRequestBase buildHttpRequest() throws URISyntaxException {
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    try {//from   w w w. ja  v  a  2s  .c o  m
        for (DiskFileItem fileItem : files) {
            if (fileItem.isFormField())
                multipartEntity.addPart(fileItem.getFieldName(), new StringBody(new String(fileItem.get())));
            else {
                //               FileBody fileBody = new FileBody(fileItem.getStoreLocation(), fileItem.getName(), fileItem.getContentType(), fileItem.getCharSet());
                InputStreamBody fileBody = new InputStreamKnownSizeBody(fileItem.getInputStream(),
                        fileItem.get().length, fileItem.getContentType(), fileItem.getName());
                multipartEntity.addPart(fileItem.getFieldName(), fileBody);
            }
        }

        // some request may have additional parameters in a query string
        if (parameterMap != null)
            for (Entry<String, String> entry : parameterMap.entries())
                multipartEntity.addPart(entry.getKey(), new StringBody(entry.getValue()));

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

    HttpPost postRequest = new HttpPost(requestedURL);
    postRequest.setEntity(multipartEntity);
    return postRequest;
}

From source file:key.access.manager.HttpHandler.java

public boolean sendImage(String url, String employeeId, File imageFile) throws IOException {
    String userHome = System.getProperty("user.home");
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httpPost = new HttpPost(url);
    FileBody fileBody = new FileBody(imageFile);
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    reqEntity.addPart("fileToUpload", fileBody);
    reqEntity.addPart("employee_id", new StringBody(employeeId));

    httpPost.setEntity(reqEntity);/*from   www .  j av a  2  s .  c o m*/

    // execute HTTP post request
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
        String responseStr = EntityUtils.toString(resEntity).trim();
        System.out.println(responseStr);
        return true;
    } else {
        return false;
    }
}

From source file:uk.co.jarofgreen.cityoutdoors.API.BaseCall.java

protected void addDataToCall(String key, String value) {
    if (value != null) {
        try {/*from  ww  w  .ja va2  s. c om*/
            multipartEntity.addPart(key, new StringBody(value));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

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

/**
 * @param postId//from  ww  w .  j a v a 2  s .c  o  m
 *            The id of the post to be modified.
 * @return HTTP status code
 * @throws NoCredentialsException
 * @throws ClientProtocolException
 * @throws IOException
 */
public int postToTumblr(String postId) throws NoCredentialsException, ClientProtocolException, IOException {
    entity.addPart("post-id", new StringBody(postId));
    return postToTumblr();
}

From source file:com.carapp.login.splashActivity.java

private void getClientBranch() {

    MultipartEntity entity = new MultipartEntity();
    try {/*from   w w  w. ja  va 2 s.  c o m*/
        entity.addPart("action", new StringBody("init_config"));

        new AsyncWebServiceProcessingTask(context, entity, messagecheck, new AsynckCallback() {

            @Override
            public void run(String result) {
                if (UIUtils.checkJson(result, context)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.optString("satus").equals("success")) {
                            PdfInfo.client = jsonObject.optString("client");
                            PdfInfo.branch = jsonObject.optString("branch");
                            Util.showCustomDialogWithoutButton(context, "Message", messagechecksucces,
                                    new Callback2() {
                                        @Override
                                        public void ok(final Dialog dialog) {
                                            final Handler handler = new Handler();
                                            final Runnable runnable = new Runnable() {
                                                @Override
                                                public void run() {
                                                    dialog.dismiss();
                                                    new AsyncWebServiceProcessingTask(context, null,
                                                            "Please wait while checking date",
                                                            new AsynckCallback() {

                                                                @Override
                                                                public void run(String result) {
                                                                    Log.e("date", "" + result);
                                                                    String sysdate = android.text.format.DateFormat
                                                                            .format("dd/MM/yyyy",
                                                                                    new java.util.Date())
                                                                            .toString();
                                                                    if (result.equals(sysdate)) {
                                                                        Toast.makeText(context, "date match",
                                                                                Toast.LENGTH_SHORT).show();
                                                                        new AsyncWebServiceProcessingTask(
                                                                                context, null, messagecheckday,
                                                                                new AsynckCallback() {
                                                                                    @Override
                                                                                    public void run(
                                                                                            String result) {
                                                                                        int day = Integer
                                                                                                .parseInt(
                                                                                                        result);
                                                                                        Calendar calendar = Calendar
                                                                                                .getInstance();
                                                                                        int Today = calendar
                                                                                                .get(Calendar.DAY_OF_WEEK);
                                                                                        day++;
                                                                                        if (day == Today) {
                                                                                            Toast.makeText(
                                                                                                    context,
                                                                                                    "day is correct",
                                                                                                    Toast.LENGTH_SHORT)
                                                                                                    .show();
                                                                                            String ma_a = null;

                                                                                            try {
                                                                                                WifiManager wiman = (WifiManager) getSystemService(
                                                                                                        Context.WIFI_SERVICE);
                                                                                                ma_a = wiman
                                                                                                        .getConnectionInfo()
                                                                                                        .getMacAddress();
                                                                                                Log.i(t, ""
                                                                                                        + ma_a);
                                                                                            } catch (Exception e1) {

                                                                                                e1.printStackTrace();
                                                                                                Log.i(t, " "
                                                                                                        + e1);
                                                                                            }
                                                                                            MultipartEntity entity = new MultipartEntity();
                                                                                            try {
                                                                                                entity.addPart(
                                                                                                        "action",
                                                                                                        new StringBody(
                                                                                                                "device_authentication"));
                                                                                                entity.addPart(
                                                                                                        "mac_address",
                                                                                                        new StringBody(
                                                                                                                ma_a));
                                                                                                new AsyncWebServiceProcessingTask(
                                                                                                        context,
                                                                                                        entity,
                                                                                                        "Checking License",
                                                                                                        new AsynckCallback() {

                                                                                                            @Override
                                                                                                            public void run(
                                                                                                                    String result) {

                                                                                                                if (UIUtils
                                                                                                                        .checkJson(
                                                                                                                                result,
                                                                                                                                context)) {
                                                                                                                    try {
                                                                                                                        JSONObject jsonObject = new JSONObject(
                                                                                                                                result);
                                                                                                                        if (jsonObject
                                                                                                                                .optString(
                                                                                                                                        "satus")
                                                                                                                                .equals("success")) {
                                                                                                                            Toast.makeText(
                                                                                                                                    context,
                                                                                                                                    "LicenseCheck sucesses",
                                                                                                                                    Toast.LENGTH_SHORT)
                                                                                                                                    .show();
                                                                                                                            startActivity(
                                                                                                                                    new Intent(
                                                                                                                                            context,
                                                                                                                                            LoginActivity.class));
                                                                                                                            finish();

                                                                                                                        } else if (jsonObject
                                                                                                                                .optString(
                                                                                                                                        "satus")
                                                                                                                                .equals("error")) {
                                                                                                                            Util.showCustomDialog(
                                                                                                                                    context,
                                                                                                                                    "Error",
                                                                                                                                    jsonObject
                                                                                                                                            .optString(
                                                                                                                                                    "msg"));

                                                                                                                        }

                                                                                                                    } catch (Exception e) {

                                                                                                                        e.printStackTrace();

                                                                                                                    }

                                                                                                                }
                                                                                                            }
                                                                                                        }).execute(
                                                                                                                PdfInfo.newjobcard);

                                                                                            } catch (Exception e) {

                                                                                                e.printStackTrace();
                                                                                            }

                                                                                        } else {
                                                                                            Util.showCustomDialogWithoutButton(
                                                                                                    context,
                                                                                                    "Error",
                                                                                                    messagecheckdayerror
                                                                                                            + " server day is "
                                                                                                            + day
                                                                                                            + " but your device is"
                                                                                                            + Today,
                                                                                                    new Callback2() {

                                                                                                        @Override
                                                                                                        public void ok(
                                                                                                                final Dialog dialog) {

                                                                                                            final Handler handler = new Handler();
                                                                                                            final Runnable runnable = new Runnable() {
                                                                                                                @Override
                                                                                                                public void run() {
                                                                                                                    dialog.dismiss();
                                                                                                                    finish();
                                                                                                                }
                                                                                                            };
                                                                                                            handler.postDelayed(
                                                                                                                    runnable,
                                                                                                                    5000);

                                                                                                        }
                                                                                                    });
                                                                                        }

                                                                                    }
                                                                                }).execute(PdfInfo.dayaddress);
                                                                    } else {

                                                                        Util.showCustomDialogWithoutButton(
                                                                                context, "Error",
                                                                                messagecheckdateerror
                                                                                        + " server date is "
                                                                                        + result
                                                                                        + " but device date is "
                                                                                        + sysdate,
                                                                                new Callback2() {

                                                                                    @Override
                                                                                    public void ok(
                                                                                            final Dialog dialog) {

                                                                                        new Timer().schedule(
                                                                                                new TimerTask() {

                                                                                                    @Override
                                                                                                    public void run() {
                                                                                                        dialog.dismiss();
                                                                                                        finish();

                                                                                                    }
                                                                                                }, 5000);
                                                                                    }
                                                                                });

                                                                    }
                                                                }
                                                            }).execute(PdfInfo.dateaddress);

                                                }
                                            };
                                            handler.postDelayed(runnable, 5000);

                                        }
                                    });

                        } else if (jsonObject.optString("satus").equals("error")) {
                            Util.showCustomDialogWithoutButton(context, "Message", messagechecksucces,
                                    new Callback2() {

                                        @Override
                                        public void ok(final Dialog dialog) {

                                            new Timer().schedule(new TimerTask() {

                                                @Override
                                                public void run() {
                                                    dialog.dismiss();
                                                    finish();

                                                }
                                            }, 5000);
                                        }
                                    });

                        }

                    } catch (Exception e) {

                        e.printStackTrace();

                    }

                }
            }
        }).execute(PdfInfo.newjobcard);

    } catch (Exception e) {

        e.printStackTrace();
    }

}