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(final HttpMultipartMode mode) 

Source Link

Usage

From source file:org.zywx.wbpalmstar.platform.push.report.PushReportHttpClient.java

public static String sendPostData(String data, String url, Context mCtx) {

    // HttpUriRequest httpRequest = new HttpPost(url);
    PushReportUtility.log("url = " + url);
    HttpPost post = new HttpPost(url);
    HttpClient httpClient = getSSLHttpClient(mCtx);
    // Post???NameValuePair[]
    // ???request.getParameter("name")
    // List<NameValuePair> params = new ArrayList<NameValuePair>();
    // params.add(new BasicNameValuePair("name", data));
    BDebug.d("debug", "data == " + data);
    PushReportUtility.log("data == " + data);
    HttpResponse httpResponse = null;//from  w ww.j a va  2  s.  co m
    post.setHeader("Accept", "*/*");
    // HttpClient httpClient = null;
    try {
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        // ?HTTP request

        post.setEntity(new ByteArrayEntity(data.getBytes()));
        // ?HTTP response
        // httpClient = getSSLHttpClient();
        httpResponse = httpClient.execute(post);
        // ??200 ok
        int responesCode = httpResponse.getStatusLine().getStatusCode();
        BDebug.d("debug", "responesCode == " + responesCode);
        PushReportUtility.log("responesCode == " + responesCode);
        if (responesCode == 200) {
            // ?
            String res = EntityUtils.toString(httpResponse.getEntity());
            PushReportUtility.log("res == " + res);
            return res;
        } else {
            System.out.println(EntityUtils.toString(httpResponse.getEntity()));
        }

    } catch (Exception e) {
        PushReportUtility.log("Exception == " + e.getMessage());
        e.printStackTrace();
    } finally {
        if (post != null) {
            post.abort();
            post = null;
        }
        if (httpResponse != null) {
            httpResponse = null;
        }
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
            httpClient = null;
        }
    }
    return null;
}

From source file:com.openmeap.http.FileHandlingHttpRequestExecuterImpl.java

@Override
public HttpResponse postData(String url, Hashtable getParams, Hashtable postParams)
        throws HttpRequestException {

    // test to determine whether this is a file upload or not.
    Boolean isFileUpload = false;
    for (Object o : postParams.values()) {
        if (o instanceof File) {
            isFileUpload = true;//from  w w w .jav  a  2  s. c  o m
            break;
        }
    }

    if (isFileUpload) {
        try {
            HttpPost httpPost = new HttpPost(createUrl(url, getParams));

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

            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            for (Object o : postParams.entrySet()) {
                Map.Entry<String, Object> entry = (Map.Entry<String, Object>) o;

                if (entry.getValue() instanceof File) {

                    // For File parameters
                    File file = (File) entry.getValue();
                    FileNameMap fileNameMap = URLConnection.getFileNameMap();
                    String type = fileNameMap.getContentTypeFor(file.toURL().toString());

                    entity.addPart(entry.getKey(), new FileBody(((File) entry.getValue()), type));
                } else {

                    // For usual String parameters
                    entity.addPart(entry.getKey(), new StringBody(entry.getValue().toString(), "text/plain",
                            Charset.forName(FormConstants.CHAR_ENC_DEFAULT)));
                }
            }

            httpPost.setEntity(entity);

            return execute(httpPost);
        } catch (Exception e) {
            throw new HttpRequestException(e);
        }
    } else {

        return super.postData(url, getParams, postParams);
    }
}

From source file:com.sytecso.jbpm.client.rs.JbpmRestTemplate.java

private String requestPost(String url, Map<String, Object> parameters, boolean multipart) throws Exception {
    log.info("--- POST");
    MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
    if (parameters == null) {
        parameters = new HashMap<String, Object>();
    }//from  www.ja  va  2 s . c o  m
    Set<String> keys = parameters.keySet();
    for (String keyString : keys) {
        String value = parameters.get(keyString).toString();
        formparams.add(new BasicNameValuePair(keyString, value));
        if (multipart) {
            try {
                StringBody stringBody = new StringBody(value, Charset.forName("UTF-8"));
                //System.out.println(stringBody.);
                multiPartEntity.addPart(keyString, (ContentBody) stringBody);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    HttpPost httpPost = new HttpPost(url);
    if (multipart) {
        httpPost.setEntity(multiPartEntity);
    } else {
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");// new UrlEncodedFormEntity(formparams, "multipart/form-data");
        ////
        httpPost.setEntity(entity);
    }
    /*if(!this.SESSION_ID.equals("")){
    httpPost.setHeader("Cookie", "JSESSIONID="+SESSION_ID); 
    }*/
    HttpResponse response = httpClient.execute(httpPost);
    return read(response.getEntity().getContent());
}

From source file:com.sat.sonata.MenuActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection.
    switch (item.getItemId()) {
    case R.id.stop:
        Log.d("SITTING", "Inside stop case");
        //stopService(new Intent(this, SonataService.class));
        return true;
    case R.id.recognise:
        String imagePath = getIntent().getStringExtra("image");
        getIntent().removeExtra("image");
        Log.d("SITTING", imagePath);

        HttpPost postRequest = new HttpPost("http://129.31.195.224:8080/picUpload");
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        try {/*w  ww  . j  a  v a 2s. c  o m*/

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            Bitmap bitmap;
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            bitmap = BitmapFactory.decodeFile(imagePath, options);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 75, bos);
            byte[] data = bos.toByteArray();
            ByteArrayBody bab = new ByteArrayBody(data, "music.jpg");

            reqEntity.addPart("music", bab);

            postRequest.setEntity(reqEntity);
            HttpPost[] posts = new HttpPost[1];
            posts[0] = postRequest;

            GetImageTask getImageTask = new GetImageTask();
            getImageTask.execute(posts);

        } catch (Exception e) {
            Log.v("Exception in Image", "" + e);
            //                    reqEntity.addPart("picture", new StringBody(""));
        }

    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:it.unipi.di.acube.batframework.systemPlugins.ERDSystem.java

@Override
public HashSet<Tag> solveC2W(String text) throws AnnotationException {
    lastTime = Calendar.getInstance().getTimeInMillis();
    HashSet<Tag> res = new HashSet<Tag>();
    try {//from   w w  w. ja v a  2  s.  com
        URL erdApi = new URL(url);

        HttpURLConnection connection = (HttpURLConnection) erdApi.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");

        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
        multipartEntity.addPart("runID", new StringBody(this.run));
        multipartEntity.addPart("TextID", new StringBody("" + text.hashCode()));
        multipartEntity.addPart("Text", new StringBody(text));

        connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
        OutputStream out = connection.getOutputStream();
        try {
            multipartEntity.writeTo(out);
        } finally {
            out.close();
        }

        int status = ((HttpURLConnection) connection).getResponseCode();
        if (status != 200) {
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            String line = null;
            while ((line = br.readLine()) != null)
                System.err.println(line);
            throw new RuntimeException();
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = null;
        while ((line = br.readLine()) != null) {
            String mid = line.split("\t")[2];
            String title = freebApi.midToTitle(mid);
            int wid;
            if (title == null || (wid = wikiApi.getIdByTitle(title)) == -1)
                System.err.println("Discarding mid=" + mid);
            else
                res.add(new Tag(wid));
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    lastTime = Calendar.getInstance().getTimeInMillis() - lastTime;
    return res;
}

From source file:org.cmuchimps.gort.modules.webinfoservice.AppEngineUpload.java

private static String uploadBlobstoreDataNoRetry(String url, String filename, String mime, byte[] data) {
    if (url == null || url.length() <= 0) {
        return null;
    }/*from ww w.j a  va  2  s  .  c  om*/

    if (data == null || data.length <= 0) {
        return null;
    }

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost httpPost = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("data", new ByteArrayBody(data, mime, filename));

    httpPost.setEntity(entity);

    try {
        HttpResponse response = httpClient.execute(httpPost);

        System.out.println("Blob upload status code: " + response.getStatusLine().getStatusCode());

        /*
        //http://grinder.sourceforge.net/g3/script-javadoc/HTTPClient/HTTPResponse.html
        // 2xx - success
        if (response.getStatusLine().getStatusCode() / 100 != 2) {
            return null;
        }
        */

        InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
        BufferedReader br = new BufferedReader(isr);

        String blobKey = br.readLine();

        blobKey = (blobKey != null) ? blobKey.trim() : null;

        br.close();
        isr.close();

        if (blobKey != null && blobKey.length() > 0) {
            return String.format("%s%s", MTURKSERVER_BLOB_DOWNLOAD_URL, blobKey);
        } else {
            return null;
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.harshad.linconnectclient.NotificationUtilities.java

public static boolean sendData(Context c, Notification n, String packageName) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);

    ConnectivityManager connManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    // Check Wifi state, whether notifications are enabled globally, and
    // whether notifications are enabled for specific application
    if (prefs.getBoolean("pref_toggle", true) && prefs.getBoolean(packageName, true) && mWifi.isConnected()) {
        String ip = prefs.getString("pref_ip", "0.0.0.0:9090");

        // Magically extract text from notification
        ArrayList<String> notificationData = NotificationUtilities.getNotificationText(n);

        // Use PackageManager to get application name and icon
        final PackageManager pm = c.getPackageManager();
        ApplicationInfo ai;//from w  ww.j a  v a2  s . c o m
        try {
            ai = pm.getApplicationInfo(packageName, 0);
        } catch (final NameNotFoundException e) {
            ai = null;
        }

        String notificationBody = "";
        String notificationHeader = "";
        // Create header and body of notification
        if (notificationData.size() > 0) {
            notificationHeader = notificationData.get(0);
            if (notificationData.size() > 1) {
                notificationBody = notificationData.get(1);
            }
        } else {
            return false;
        }

        for (int i = 2; i < notificationData.size(); i++) {
            notificationBody += "\n" + notificationData.get(i);
        }

        // Append application name to body
        if (pm.getApplicationLabel(ai) != null) {
            if (notificationBody.isEmpty()) {
                notificationBody = "via " + pm.getApplicationLabel(ai);
            } else {
                notificationBody += " (via " + pm.getApplicationLabel(ai) + ")";
            }
        }

        // Setup HTTP request
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // If the notification contains an icon, use it
        if (n.largeIcon != null) {
            entity.addPart("notificon",
                    new InputStreamBody(ImageUtilities.bitmapToInputStream(n.largeIcon), "drawable.png"));
        }
        // Otherwise, use the application's icon
        else {
            entity.addPart("notificon",
                    new InputStreamBody(
                            ImageUtilities.bitmapToInputStream(
                                    ImageUtilities.drawableToBitmap(pm.getApplicationIcon(ai))),
                            "drawable.png"));
        }

        HttpPost post = new HttpPost("http://" + ip + "/notif");
        post.setEntity(entity);

        try {
            post.addHeader("notifheader", Base64.encodeToString(notificationHeader.getBytes("UTF-8"),
                    Base64.URL_SAFE | Base64.NO_WRAP));
            post.addHeader("notifdescription", Base64.encodeToString(notificationBody.getBytes("UTF-8"),
                    Base64.URL_SAFE | Base64.NO_WRAP));
        } catch (UnsupportedEncodingException e) {
            post.addHeader("notifheader",
                    Base64.encodeToString(notificationHeader.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
            post.addHeader("notifdescription",
                    Base64.encodeToString(notificationBody.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
        }

        // Send HTTP request
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        try {
            response = client.execute(post);
            String html = EntityUtils.toString(response.getEntity());
            if (html.contains("true")) {
                return true;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    return false;
}

From source file:me.ziccard.secureit.async.upload.ImagesUploaderTask.java

@Override
protected Void doInBackground(Void... params) {
    HttpClient client = new DefaultHttpClient();

    Log.i("ImagesUploaderTask", "Started");

    int imagesToUpload = 0;

    /*//w w  w  . j  a  va  2  s. co  m
     * If we are using mobile connectivity we upload half of the images
     * stored 
     */
    if (connectivityType == WIFI_CONNECTIVITY) {
        imagesToUpload = prefs.getMaxImages();
    }
    if (connectivityType == MOBILE_CONNECTIVITY) {
        imagesToUpload = prefs.getMaxImages() / 2;
    }
    if (connectivityType == NO_CONNECTIVITY) {
        imagesToUpload = 0;
    }

    for (int imageCount = 0; imageCount < imagesToUpload; imageCount++) {

        String path = Environment.getExternalStorageDirectory().getPath() + prefs.getImagePath() + imageCount
                + ".jpg";

        HttpPost request = new HttpPost(Remote.HOST + Remote.PHONES + "/" + phoneId + Remote.UPLOAD_IMAGES);

        Log.i("ImagesUploaderTask", "Uploading image " + path);

        /*
         * Get image from filesystem
         */
        File image = new File(path);

        //Only if the image exists we upload it 
        if (image.exists()) {

            Log.i("ImagesUploaderTask", "Image exists");

            /*
             * Getting the image from the file system
             */
            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("image", new FileBody(image, "image/jpeg"));
            request.setEntity(reqEntity);

            /*
             * Setting the access token
             */
            request.setHeader("access_token", accessToken);

            try {
                HttpResponse response = client.execute(request);

                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                StringBuilder builder = new StringBuilder();
                for (String line = null; (line = reader.readLine()) != null;) {
                    builder.append(line).append("\n");
                }

                Log.i("ImagesRecorderTask", "Response:\n" + builder.toString());

                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new HttpException();
                }
            } catch (Exception e) {
                Log.e("ImageUploaderTask", "Error uploading image: " + path);
            }
            //otherwise no other image exists
        } else {
            return null;
        }
    }
    return null;
}

From source file:com.fly1tkg.streamfileupload.FileUploadFacade.java

public void post(final String url, final String fileKey, final File file, final String contentType,
        final Map<String, String> params, final FileUploadCallback callback) {

    if (null == callback) {
        throw new RuntimeException("FileUploadCallback should not be null.");
    }/*from  ww  w.  j  a v a  2 s. c  om*/

    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(new Runnable() {
        public void run() {
            try {
                HttpPost httpPost = new HttpPost(url);

                FileBody fileBody;
                if (null == contentType) {
                    fileBody = new FileBody(file);
                } else {
                    fileBody = new FileBody(file, contentType);
                }

                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                if (null == fileKey) {
                    entity.addPart(DEFAULT_FILE_KEY, fileBody);
                } else {
                    entity.addPart(fileKey, fileBody);
                }

                if (null != params) {
                    for (Map.Entry<String, String> e : params.entrySet()) {
                        entity.addPart(e.getKey(), new StringBody(e.getValue()));
                    }
                }

                httpPost.setEntity(entity);

                upload(httpPost, callback);
            } catch (UnsupportedEncodingException e) {
                callback.onFailure(-1, null, e);
            }
        }
    });
}

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

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

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

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("PARAMS:\n", response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}