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:org.deviceconnect.android.profile.restful.test.NormalFileDescriptorProfileTestCase.java

/**
 * ????.//from www.java 2s. c  o  m
 * <pre>
 * ?HTTP
 * Method: PUT
 * Path: /file_descriptor/write?deviceid=xxxx&mediaid=xxxx
 * Entity: "test"
 * </pre>
 * <pre>
 * ??
 * result?0???????
 * </pre>
 */
public void testWrite001() {
    StringBuilder builder = new StringBuilder();
    builder.append(DCONNECT_MANAGER_URI);
    builder.append("/" + FileDescriptorProfileConstants.PROFILE_NAME);
    builder.append("/" + FileDescriptorProfileConstants.ATTRIBUTE_WRITE);
    builder.append("?");
    builder.append(DConnectProfileConstants.PARAM_DEVICE_ID + "=" + getDeviceId());
    builder.append("&");
    builder.append(FileDescriptorProfileConstants.PARAM_PATH + "=test.txt");
    builder.append("&");
    builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN + "=" + getAccessToken());
    try {
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("media", new StringBody("test"));
        HttpPut request = new HttpPut(builder.toString());
        request.addHeader("Content-Disposition", "form-data; name=\"media\"; filename=\"test.txt\"");
        request.setEntity(entity);
        JSONObject root = sendRequest(request);
        Assert.assertNotNull("root is null.", root);
        assertResultOK(root);
    } catch (JSONException e) {
        fail("Exception in JSONObject." + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        fail("Exception in StringBody." + e.getMessage());
    }
}

From source file:palamarchuk.smartlife.app.RegisterActivity.java

private MultipartEntity collectData() throws UnsupportedEncodingException {
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("email", new StringBody(email.getText().toString()));
    entity.addPart("password", new StringBody(password.getText().toString()));
    entity.addPart("first_name", new StringBody(name.getText().toString()));
    entity.addPart("birthdate", new StringBody(birthDateToServer));
    entity.addPart("gender", new StringBody(String.valueOf(gender)));
    entity.addPart("phone", new StringBody(phone.getText().toString()));
    entity.addPart("last_name", new StringBody(lastName.getText().toString()));
    entity.addPart("city_id", new StringBody(cities.getCityId()));
    entity.addPart("secret", new StringBody(registerActivitySecret.getText().toString()));
    entity.addPart("card_number", new StringBody(cardNumber));
    entity.addPart("pin", new StringBody(cardPinCode));
    return entity;
}

From source file:bluej.collect.DataCollectorImpl.java

public static void bluejOpened(String osVersion, String javaVersion, String bluejVersion,
        String interfaceLanguage, List<ExtensionWrapper> extensions) {
    if (Config.isGreenfoot())
        return; //Don't even look for UUID
    DataSubmitter.initSequence();//from  ww  w.j av a2s  .co  m

    MultipartEntity mpe = new MultipartEntity();

    mpe.addPart("installation[operating_system]", CollectUtility.toBody(osVersion));
    mpe.addPart("installation[java_version]", CollectUtility.toBody(javaVersion));
    mpe.addPart("installation[bluej_version]", CollectUtility.toBody(bluejVersion));
    mpe.addPart("installation[interface_language]", CollectUtility.toBody(interfaceLanguage));

    addExtensions(mpe, extensions);

    submitEvent(null, null, EventName.BLUEJ_START, new PlainEvent(mpe));
}

From source file:net.fluidnexus.FluidNexusAndroid.services.NexusServiceThread.java

/**
 * Start the listeners for zeroconf services
 */// w w  w .  jav a 2  s. c om
public void doStateNone() {
    if (wifiManager.getWifiState() == wifiManager.WIFI_STATE_ENABLED) {
        Cursor c = messagesProviderHelper.publicMessages();

        while (c.isAfterLast() == false) {
            String message_hash = c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_MESSAGE_HASH));
            boolean result = checkHash(message_hash);

            if (!result) {
                try {
                    JSONObject message = new JSONObject();
                    message.put("message_title",
                            c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_TITLE)));
                    message.put("message_content",
                            c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_CONTENT)));
                    message.put("message_hash",
                            c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_MESSAGE_HASH)));
                    message.put("message_type", c.getInt(c.getColumnIndex(MessagesProviderHelper.KEY_TYPE)));
                    message.put("message_time", c.getFloat(c.getColumnIndex(MessagesProviderHelper.KEY_TIME)));
                    message.put("message_received_time",
                            c.getFloat(c.getColumnIndex(MessagesProviderHelper.KEY_RECEIVED_TIME)));
                    message.put("message_priority",
                            c.getInt(c.getColumnIndex(MessagesProviderHelper.KEY_PRIORITY)));

                    String attachment_path = c
                            .getString(c.getColumnIndex(MessagesProviderHelper.KEY_ATTACHMENT_PATH));

                    //String serializedMessage = message.toString();

                    // First, get our nonce
                    consumer = new CommonsHttpOAuthConsumer(key, secret);
                    consumer.setTokenWithSecret(token, token_secret);
                    HttpPost nonce_request = new HttpPost(NEXUS_NONCE_URL);
                    consumer.sign(nonce_request);
                    HttpClient client = new DefaultHttpClient();
                    String response = client.execute(nonce_request, new BasicResponseHandler());
                    JSONObject object = new JSONObject(response);
                    String nonce = object.getString("nonce");

                    // Then, take our nonce and key and put them in the message
                    message.put("message_nonce", nonce);
                    message.put("message_key", key);

                    // Setup our multipart entity
                    MultipartEntity entity = new MultipartEntity();

                    // Deal with file attachment
                    if (!attachment_path.equals("")) {
                        File file = new File(attachment_path);
                        ContentBody cbFile = new FileBody(file);
                        entity.addPart("message_attachment", cbFile);

                        // add the original filename to the message
                        message.put("message_attachment_original_filename", c.getString(
                                c.getColumnIndex(MessagesProviderHelper.KEY_ATTACHMENT_ORIGINAL_FILENAME)));
                    }

                    String serializedMessage = message.toString();
                    ContentBody messageBody = new StringBody(serializedMessage);
                    entity.addPart("message", messageBody);

                    HttpPost message_request = new HttpPost(NEXUS_MESSAGE_URL);
                    message_request.setEntity(entity);

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

                    response = client.execute(message_request, new BasicResponseHandler());
                    object = new JSONObject(response);
                    boolean message_result = object.getBoolean("result");

                    if (message_result) {
                        ContentValues values = new ContentValues();
                        values.put(MessagesProviderHelper.KEY_MESSAGE_HASH, message_hash);
                        values.put(MessagesProviderHelper.KEY_UPLOADED, 1);
                        int res = messagesProviderHelper
                                .setPublic(c.getLong(c.getColumnIndex(MessagesProviderHelper.KEY_ID)), values);
                        if (res == 0) {
                            log.debug("Message with hash " + message_hash
                                    + " not found; this should never happen!");
                        }
                    }

                } catch (OAuthMessageSignerException e) {
                    log.debug("OAuthMessageSignerException: " + e);
                } catch (OAuthExpectationFailedException e) {
                    log.debug("OAuthExpectationFailedException: " + e);
                } catch (OAuthCommunicationException e) {
                    log.debug("OAuthCommunicationException: " + e);
                } catch (JSONException e) {
                    log.debug("JSON Error: " + e);
                } catch (IOException e) {
                    log.debug("IOException: " + e);
                }
            }
            c.moveToNext();
        }

        c.close();

    }

    setServiceState(STATE_SERVICE_WAIT);
}

From source file:org.fcrepo.integration.api.FedoraDatastreamsIT.java

License:asdf

@Test
public void testModifyMultipleDatastreams() throws Exception {
    final HttpPost objMethod = postObjMethod("FedoraDatastreamsTest8");

    assertEquals(201, getStatus(objMethod));

    final HttpPost createDSVOIDMethod = postDSMethod("FedoraDatastreamsTest8", "ds_void",
            "marbles for everyone");
    assertEquals(201, getStatus(createDSVOIDMethod));

    final HttpPost post = new HttpPost(
            serverAddress + "objects/FedoraDatastreamsTest8/datastreams?delete=ds_void");

    final MultipartEntity multiPartEntity = new MultipartEntity();
    multiPartEntity.addPart("ds1", new StringBody("asdfg"));
    multiPartEntity.addPart("ds2", new StringBody("qwerty"));

    post.setEntity(multiPartEntity);//from  www.  j ava 2  s  . c o m

    final HttpResponse postResponse = client.execute(post);

    assertEquals(201, postResponse.getStatusLine().getStatusCode());

    final HttpGet getDSesMethod = new HttpGet(serverAddress + "objects/FedoraDatastreamsTest8/datastreams");
    final HttpResponse response = client.execute(getDSesMethod);
    assertEquals(200, response.getStatusLine().getStatusCode());
    final String content = EntityUtils.toString(response.getEntity());
    assertTrue("Didn't find the first datastream!", compile("dsid=\"ds1\"", DOTALL).matcher(content).find());
    assertTrue("Didn't find the second datastream!", compile("dsid=\"ds2\"", DOTALL).matcher(content).find());

    assertFalse("Found the deleted datastream!", compile("dsid=\"ds_void\"", DOTALL).matcher(content).find());

}

From source file:com.alphabetbloc.accessmrs.utilities.NetworkUtils.java

public static MultipartEntity createMultipartEntity(String path) {

    // find all files in parent directory
    File file = new File(path);
    File[] files = file.getParentFile().listFiles();
    if (App.DEBUG)
        Log.v(TAG, file.getAbsolutePath());

    // mime post/*  w ww  .  j  a va2s .  com*/
    MultipartEntity entity = null;
    if (files != null) {
        entity = new MultipartEntity();
        for (int j = 0; j < files.length; j++) {
            File f = files[j];
            FileBody fb;
            if (f.getName().endsWith(".xml")) {
                fb = new FileBody(f, "text/xml");
                entity.addPart("xml_submission_file", fb);
                if (App.DEBUG)
                    Log.v(TAG, "added xml file " + f.getName());
            } else if (f.getName().endsWith(".jpg")) {
                fb = new FileBody(f, "image/jpeg");
                entity.addPart(f.getName(), fb);
                if (App.DEBUG)
                    Log.v(TAG, "added image file " + f.getName());
            } else if (f.getName().endsWith(".3gpp")) {
                fb = new FileBody(f, "audio/3gpp");
                entity.addPart(f.getName(), fb);
                if (App.DEBUG)
                    Log.v(TAG, "added audio file " + f.getName());
            } else if (f.getName().endsWith(".3gp")) {
                fb = new FileBody(f, "video/3gpp");
                entity.addPart(f.getName(), fb);
                if (App.DEBUG)
                    Log.v(TAG, "added video file " + f.getName());
            } else if (f.getName().endsWith(".mp4")) {
                fb = new FileBody(f, "video/mp4");
                entity.addPart(f.getName(), fb);
                if (App.DEBUG)
                    Log.v(TAG, "added video file " + f.getName());
            } else {
                Log.w(TAG, "unsupported file type, not adding file: " + f.getName());
            }
        }
    } else {
        if (App.DEBUG)
            Log.v(TAG, "no files to upload in instance");
    }

    return entity;
}

From source file:com.puppetlabs.geppetto.forge.client.ForgeHttpClient.java

@Override
public <V> V postUpload(String uri, Map<String, String> stringParts, InputStream in, String mimeType,
        String fileName, final long fileSize, Class<V> type) throws IOException {
    HttpPost request = new HttpPost(createV2Uri(uri));
    configureRequest(request);//  www. j  av a2  s.c om

    MultipartEntity entity = new MultipartEntity();
    for (Map.Entry<String, String> entry : stringParts.entrySet())
        entity.addPart(entry.getKey(), StringBody.create(entry.getValue(), "text/plain", UTF_8));

    entity.addPart("file", new InputStreamBody(in, mimeType, fileName) {
        @Override
        public long getContentLength() {
            return fileSize;
        }
    });
    request.setEntity(entity);
    return executeRequest(request, type);
}

From source file:com.francisli.processing.http.HttpClient.java

/**
 * @param files HashMap: a collection of files to send to the server
 *///from   w ww  .ja  v  a  2s.  c  om
public HttpRequest POST(String path, Map params, Map files) {
    //// clean up path a little bit- remove whitespace, add slash prefix
    path = path.trim();
    if (!path.startsWith("/")) {
        path = "/" + path;
    }
    //// finally, invoke request
    HttpPost post = new HttpPost(getHost().toURI() + path);
    MultipartEntity multipart = null;
    //// if files passed, set up a multipart request
    if (files != null) {
        multipart = new MultipartEntity();
        post.setEntity(multipart);
        for (Object key : files.keySet()) {
            Object value = files.get(key);
            if (value instanceof byte[]) {
                multipart.addPart((String) key, new ByteArrayBody((byte[]) value, "bytes.dat"));
            } else if (value instanceof String) {
                File file = new File((String) value);
                if (!file.exists()) {
                    file = parent.sketchFile((String) value);
                }
                multipart.addPart((String) key, new FileBody(file));
            }
        }
    }
    //// if params passed, format into a query string and append
    if (params != null) {
        if (multipart == null) {
            ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
            for (Object key : params.keySet()) {
                Object value = params.get(key);
                pairs.add(new BasicNameValuePair(key.toString(), value.toString()));
            }
            String queryString = URLEncodedUtils.format(pairs, HTTP.UTF_8);
            if (path.contains("?")) {
                path = path + "&" + queryString;
            } else {
                path = path + "?" + queryString;
            }
            try {
                post.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
            } catch (UnsupportedEncodingException ex) {
                System.err.println("HttpClient: Unable to set POST data from parameters");
            }
        } else {
            for (Object key : params.keySet()) {
                Object value = params.get(key);
                try {
                    multipart.addPart((String) key, new StringBody((String) value));
                } catch (UnsupportedEncodingException ex) {
                    System.err.println("HttpClient: Unable to add " + key + ", " + value);
                }
            }
        }
    }
    if (useOAuth) {
        OAuthConsumer consumer = new CommonsHttpOAuthConsumer(oauthConsumerKey, oauthConsumerSecret);
        consumer.setTokenWithSecret(oauthAccessToken, oauthAccessTokenSecret);
        try {
            consumer.sign(post);
        } catch (Exception e) {
            System.err.println("HttpClient: Unable to sign POST request for OAuth");
        }
    }
    HttpRequest request = new HttpRequest(this, getHost(), post);
    request.start();
    return request;
}

From source file:com.careerly.utils.HttpClientUtils.java

/**
 * /*  ww w.ja  v a  2 s.  c om*/
 *
 * @param url
 * @param key
 * @param files
 * @return
 */
public static String postFile(String url, String key, List<File> files) {
    HttpPost post = new HttpPost(url);
    String content = null;

    MultipartEntity multipartEntity = new MultipartEntity();
    for (File file : files) {
        multipartEntity.addPart(key, new FileBody(file));
    }
    try {
        post.setEntity(multipartEntity);
        HttpResponse response = HttpClientUtils.client.execute(post);
        content = EntityUtils.toString(response.getEntity());
    } catch (Exception e) {
        HttpClientUtils.logger.error(String.format("post [%s] happens error ", url), e);
    }

    return content;
}