Example usage for org.apache.http.entity.mime MultipartEntity MultipartEntity

List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity

Introduction

In this page you can find the example usage for org.apache.http.entity.mime MultipartEntity MultipartEntity.

Prototype

public MultipartEntity() 

Source Link

Usage

From source file:ch.tatool.app.service.export.DataImportTest.java

private static HttpEntity getHttpEntity() {
    // we use a multipart entity to send over the files
    MultipartEntity entity = new MultipartEntity();

    // get participant information for training (anonymous coded data)
    String participant = "1";

    // add some additional data
    try {//from  ww  w  .j  av a  2  s. c o  m
        Charset utf8CharSet = Charset.forName("UTF-8");
        entity.addPart("participant", new StringBody(participant, utf8CharSet));
    } catch (UnsupportedEncodingException e) {
        // should not happen
    }

    return entity;
}

From source file:org.linkdroid.PostJob.java

/**
 * Posts the data to our webhook./*  w w w  . j av  a 2 s  .c o 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.deviceconnect.android.manager.test.MultipartTest.java

/**
 * PUT????????./*from ww  w .  ja  v a 2  s.  com*/
 */
public void testParsingMutilpartAsRequestParametersMethodPut() {
    URIBuilder builder = TestURIBuilder.createURIBuilder();
    builder.setProfile(DeviceOrientationProfileConstants.PROFILE_NAME);
    builder.setAttribute(DeviceOrientationProfileConstants.ATTRIBUTE_ON_DEVICE_ORIENTATION);
    try {
        MultipartEntity entity = new MultipartEntity();
        entity.addPart(DConnectProfileConstants.PARAM_DEVICE_ID, new StringBody(getDeviceId()));
        entity.addPart(DConnectProfileConstants.PARAM_SESSION_KEY, new StringBody(getClientId()));
        entity.addPart(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN, new StringBody(getAccessToken()));
        HttpPut request = new HttpPut(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.carapp.login.splashActivity.java

private void getClientBranch() {

    MultipartEntity entity = new MultipartEntity();
    try {//from   www  .  j a va2s. com
        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();
    }

}

From source file:org.ow2.proactive_grid_cloud_portal.cli.cmd.LoginWithCredentialsCommand.java

@Override
protected String login(ApplicationContext currentContext) throws CLIException {
    File credentials = new File(pathname);
    if (!credentials.exists()) {
        throw new CLIException(REASON_INVALID_ARGUMENTS,
                String.format("File does not exist: %s", credentials.getAbsolutePath()));
    }//from www . j  a  va  2  s  .c o m
    if (warn) {
        writeLine(currentContext, "Using the default credentials file: %s", credentials.getAbsolutePath());
    }
    HttpPost request = new HttpPost(currentContext.getResourceUrl("login"));
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("credential",
            new ByteArrayBody(FileUtility.byteArray(credentials), APPLICATION_OCTET_STREAM.getMimeType()));
    request.setEntity(entity);
    HttpResponseWrapper response = execute(request, currentContext);
    if (statusCode(OK) == statusCode(response)) {
        return StringUtility.responseAsString(response).trim();
    } else {
        handleError("An error occurred while logging: ", response, currentContext);
        throw new CLIException(REASON_OTHER, "An error occurred while logging.");
    }
}

From source file:eu.prestoprime.p4gui.connection.WorkflowConnection.java

public static String executeWorkflow(P4Service service, P4Workflow workflow, Map<String, String> dParamsString,
        Map<String, File> dParamsFile) throws WorkflowRequestException {

    if (dParamsString == null)
        dParamsString = new HashMap<>();
    if (dParamsFile == null)
        dParamsFile = new HashMap<>();

    dParamsString.put("wfID", workflow.toString());

    try {/*from w  w w.j av  a 2s.  c om*/
        MultipartEntity part = new MultipartEntity();

        for (String key : dParamsString.keySet()) {
            String value = dParamsString.get(key);
            part.addPart(key, new StringBody(value));
        }

        for (String key : dParamsFile.keySet()) {
            File value = dParamsFile.get(key);
            part.addPart(key, new FileBody(value));
        }

        String path = service.getURL() + "/wf/execute/" + workflow;

        logger.debug("Calling " + path);

        P4HttpClient client = new P4HttpClient(service.getUserID());
        HttpRequestBase request = new HttpPost(path);
        request.setHeader("content-data", "multipart/form-data");
        ((HttpPost) request).setEntity(part);
        HttpResponse response = client.executeRequest(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String line;
                if ((line = reader.readLine()) != null) {
                    logger.debug("Requested new job: " + line);
                    return line;
                }
            }
        } else {
            logger.debug(response.getStatusLine().toString());
            throw new WorkflowRequestException("Unable to request execution of workflow " + workflow + "...");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    throw new WorkflowRequestException(
            "Something wrong in WorkflowConnection requesting a workflow: no wfID returned...");
}

From source file:hu.sztaki.lpds.dcibridge.util.io.HttpHandler.java

public void write(String pURL, List<File> pValue) throws IOException {
    open(pURL);// ww w  . ja  va  2s .c o  m
    MultipartEntity reqEntity = new MultipartEntity();
    for (File t : pValue) {
        FileBody bin = new FileBody(t);
        reqEntity.addPart(t.getName(), bin);
    }
    httpPost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httpPost);
}

From source file:com.ibm.watson.developer_cloud.visual_recognition.v1.VisualRecognition.java

/**
 * Classifies the images against the label groups and labels. The response
 * includes a score for a label if the score meets the minimum threshold of
 * 0.5. If no score meets the threshold for an image, no labels are
 * returned.//ww w  .  j a v  a 2  s . co m
 * 
 * @param image
 *            the file image
 * @param labelSet
 *            the labels to classify against
 * @return the visual recognition images
 */
public RecognizedImage recognize(final File image, final LabelSet labelSet) {
    if (image == null)
        throw new IllegalArgumentException("image can not be null");
    try {

        Request request = Request.Post("/v1/tag/recognize");

        MultipartEntity reqEntity = new MultipartEntity();

        // Set the image_file
        FileBody bin = new FileBody(image);
        reqEntity.addPart(IMG_FILE, bin);

        if (labelSet != null) {
            StringBody labels = new StringBody(GsonSingleton.getGson().toJson(labelSet),
                    Charset.forName("UTF-8"));

            // Set the labels_to_check
            reqEntity.addPart(LABELS_TO_CHECK, labels);
        }
        request.withEntity(reqEntity);

        HttpResponse response = execute(request.build());
        String resultJson = ResponseUtil.getString(response);
        VisualRecognitionImages recognizedImages = GsonSingleton.getGson().fromJson(resultJson,
                VisualRecognitionImages.class);
        return recognizedImages.getImages().get(0);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.wikipedia.vlsergey.secretary.jwpf.actions.Edit.java

public Edit(boolean bot, String pageTitle, String token, String prependText, String text, String appendText,
        String summary, boolean minor, boolean nocreate) {
    super(bot);/* ww w.  j  a v a2 s  .  co m*/

    log.info("[action=edit]: " + pageTitle + "; " + token + "; " + toLog(prependText) + "; " + toLog(text)
            + "; " + toLog(appendText) + "; " + summary + "; " + minor + "; " + nocreate + ")");

    HttpPost postMethod = new HttpPost("/api.php");

    MultipartEntity multipartEntity = new MultipartEntity();
    setFormatXml(multipartEntity);
    setParameter(multipartEntity, "action", "edit");
    setParameter(multipartEntity, "title", pageTitle);

    if (prependText != null)
        setParameter(multipartEntity, "prependtext", prependText);

    if (text != null)
        setParameter(multipartEntity, "text", text);

    if (appendText != null)
        setParameter(multipartEntity, "appendtext", appendText);

    setParameter(multipartEntity, "summary", summary);
    if (minor) {
        setParameter(multipartEntity, "minor", "1");
    } else {
        setParameter(multipartEntity, "minor", "0");
    }

    if (bot) {
        setParameter(multipartEntity, "bot", "1");
    } else {
        setParameter(multipartEntity, "bot", "0");
    }

    if (nocreate) {
        setParameter(multipartEntity, "nocreate", "1");
    }

    setParameter(multipartEntity, "token", token);

    postMethod.setEntity(multipartEntity);

    msgs.add(postMethod);
}

From source file:fedroot.dacs.http.DacsPostRequest.java

/**
 * this is a "hybrid" multipart/form-data with parameters passed in the query string
 * and only file(s) included in the multipart entity
 * @param webServiceRequest/*  w  w  w.ja  v a 2s . c  o m*/
 * @return
 */
private HttpPost multipartPost(WebServiceRequest webServiceRequest) {
    HttpPost multipartPost = new HttpPost(webServiceRequest.getURI());
    MultipartEntity multipartEntity = new MultipartEntity();

    for (NameFilePair nameFilePair : webServiceRequest.getNameFilePairs()) {
        multipartEntity.addPart(nameFilePair.getName(), nameFilePair.getFileBody());
    }
    multipartPost.setEntity(multipartEntity);
    return multipartPost;
}