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.casquesrouges.missing.HttpAdapter.java

@Override
public void run() {
    handler.sendMessage(Message.obtain(handler, HttpAdapter.START));
    httpClient = new DefaultHttpClient();

    httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, 80),
            new UsernamePasswordCredentials(login, pass));

    HttpConnectionParams.setSoTimeout(httpClient.getParams(), 25000);
    try {/*from  www  .  j ava  2 s  . com*/
        HttpResponse response = null;
        switch (method) {
        case GET:
            response = httpClient.execute(new HttpGet(url));
            break;
        case POST:
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(data));
            response = httpClient.execute(httpPost);
            break;
        case FILE:
            File input = new File(picFile);

            HttpPost post = new HttpPost(url);
            MultipartEntity multi = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            multi.addPart("person_id", new StringBody(Integer.toString(personID)));
            multi.addPart("creator_id", new StringBody(creator_id));
            multi.addPart("file", new FileBody(input));
            post.setEntity(multi);

            Log.d("MISSING", "http FILE: " + url + " pic: " + picFile);

            response = httpClient.execute(post);

            break;
        }

        processEntity(response);

    } catch (Exception e) {
        handler.sendMessage(Message.obtain(handler, HttpAdapter.ERROR, e));
    }
    ConnectionManager.getInstance().didComplete(this);
}

From source file:com.cottsoft.weedfs.client.WeedfsClient.java

/**
 * Description<br>/*w w w  .j a va 2  s. c  om*/
 * Cache local file to WeedFS Server
 * 
 * @version v1.0.0
 * @param file
 * @return
 */
public RequestResult cache(File file) {
    RequestResult result = null;
    Gson gson = new Gson();

    if (!file.exists()) {
        throw new IllegalArgumentException("File doesn't exist");
    }

    // HTTP REQUEST begin
    result = new RequestResult();
    WeedAssign assignedInfo = null;

    BufferedReader in = null;

    // 1. Send assign request and get fid
    try {
        StringBuffer host = new StringBuffer();
        host.append("http://");
        host.append(this.masterHost);
        host.append(":");
        host.append(this.masterPort);
        host.append("/");

        //HttpUtil.request("http://" + this.masterHost + ":" + this.masterPort+ "/", "dir/assign", "GET")
        in = new BufferedReader(
                new InputStreamReader(HttpUtil.request(host.toString(), assign, EHttpMethod.GET)));

        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        // format HTTP Response to Assigned Info.
        assignedInfo = gson.fromJson(response.toString(), WeedAssign.class);

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    } finally {
        try {
            // close input stream.
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 2. Send cache file request on volume server      
    FileBody fileBody = new FileBody(file, "text/plain");
    HttpClient client = new DefaultHttpClient();

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

    StringBuffer uri = new StringBuffer();
    uri.append("http://");
    uri.append(assignedInfo.getPublicUrl());
    uri.append("/");
    uri.append(assignedInfo.getFid());
    HttpPost post = new HttpPost(uri.toString());

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    entity.addPart("fileBody", fileBody);
    post.setEntity(entity);

    try {
        // Add File char.
        String response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
        client.getConnectionManager().shutdown();

        FileResult fileResult = gson.fromJson(response, FileResult.class);

        result.setFid(assignedInfo.getFid());
        result.setSize(fileResult.getSize());
        result.setStatus(true);
        result.setFileUrl(uri.toString());
        return result;
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.toString());
    }
}

From source file:ws.munday.youtubecaptionrate.WebRequest.java

public String PostFileWithBasicAuthorization(String uri, String filename, String Username, String Password)
        throws ClientProtocolException, IOException, URISyntaxException {
    _post = new HttpPost(uri);
    _post.addHeader("Authorization", "Basic " + Base64.encodeString(Username + ":" + Password));
    File f = new File(new URI(filename));
    MultipartEntity e = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    FileBody fb = new FileBody(f);
    e.addPart("torrent_file", fb);
    StringBody sb = new StringBody("add-file");
    e.addPart("action", sb);
    _post.setEntity(e);//from  ww w  .j  a  v  a  2s.  com
    _response = _client.execute(_post);

    return GetResponseText(_response.getEntity().getContent());
}

From source file:com.jigarmjoshi.service.task.UploaderTask.java

private final boolean uploadEntryReport(Report entry) {
    if (entry == null || entry.getUploaded()) {
        return true;
    }//from w w  w .j a v  a 2  s.  co m
    boolean resultFlag = false;
    try {
        Log.i(UploaderTask.class.getSimpleName(), "uploading " + entry.getImageFileName());
        Bitmap bm = BitmapFactory.decodeFile(entry.getImageFileName());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bm.compress(CompressFormat.JPEG, 60, bos);
        byte[] data = bos.toByteArray();
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(this.serverUrl + "/uploadEntryRecord");
        ByteArrayBody bab = new ByteArrayBody(data, "report.jpg");
        // File file= new File("/mnt/sdcard/forest.png");
        // FileBody bin = new FileBody(file);
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        reqEntity.addPart("lat", new StringBody(Utility.encode(entry.getLat())));
        reqEntity.addPart("lon", new StringBody(Utility.encode(entry.getLon())));
        reqEntity.addPart("priority", new StringBody(Utility.encode(entry.getPriority())));
        reqEntity.addPart("fileName", new StringBody(Utility.encode(entry.getImageFileName())));
        reqEntity.addPart("reporterId", new StringBody(Utility.encode(entry.getId())));
        reqEntity.addPart("uploaded", bab);
        postRequest.setEntity(reqEntity);
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String sResponse;
        StringBuilder responseString = new StringBuilder();

        while ((sResponse = reader.readLine()) != null) {
            responseString = responseString.append(sResponse);
        }
        Log.i(UploaderTask.class.getSimpleName(), responseString.toString());
        if ("SUCCESS".equalsIgnoreCase(responseString.toString())) {
            resultFlag = true;
            if (entry.getImageFileName() != null) {
                File imageFileToDelete = new File(entry.getImageFileName());
                boolean deleted = imageFileToDelete.delete();

                if (deleted) {
                    Log.i(UploaderTask.class.getSimpleName(), "deleted = ?" + deleted);
                    MediaScannerConnection.scanFile(context, new String[] {

                            imageFileToDelete.getAbsolutePath() },

                            null, new MediaScannerConnection.OnScanCompletedListener() {

                                public void onScanCompleted(String path, Uri uri)

                            {

                                }

                            });

                }
            }
        }

    } catch (Exception ex) {
        Log.e(UploaderTask.class.getSimpleName(), "failed to upload", ex);
        resultFlag = false;
    }
    return resultFlag;
}

From source file:com.piusvelte.sonet.core.PhotoUploadService.java

private void start(Intent intent) {
    if (intent != null) {
        String action = intent.getAction();
        if (Sonet.ACTION_UPLOAD.equals(action)) {
            if (intent.hasExtra(Accounts.TOKEN) && intent.hasExtra(Statuses.MESSAGE)
                    && intent.hasExtra(Widgets.INSTANT_UPLOAD)) {
                String place = null;
                if (intent.hasExtra(Splace))
                    place = intent.getStringExtra(Splace);
                String tags = null;
                if (intent.hasExtra(Stags))
                    tags = intent.getStringExtra(Stags);
                // upload a photo
                Notification notification = new Notification(R.drawable.notification, "uploading photo",
                        System.currentTimeMillis());
                notification.setLatestEventInfo(getBaseContext(), "photo upload", "uploading",
                        PendingIntent.getActivity(PhotoUploadService.this, 0,
                                (Sonet.getPackageIntent(PhotoUploadService.this, About.class)), 0));
                ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFY_ID,
                        notification);//from  ww w  . java 2 s.c  om
                (new AsyncTask<String, Void, String>() {

                    @Override
                    protected String doInBackground(String... params) {
                        String response = null;
                        if (params.length > 2) {
                            Log.d(TAG, "upload file: " + params[2]);
                            HttpPost httpPost = new HttpPost(String.format(FACEBOOK_PHOTOS, FACEBOOK_BASE_URL,
                                    Saccess_token, mSonetCrypto.Decrypt(params[0])));
                            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                            File file = new File(params[2]);
                            ContentBody fileBody = new FileBody(file);
                            entity.addPart(Ssource, fileBody);
                            HttpClient httpClient = SonetHttpClient
                                    .getThreadSafeClient(getApplicationContext());
                            try {
                                entity.addPart(Smessage, new StringBody(params[1]));
                                if (params[3] != null)
                                    entity.addPart(Splace, new StringBody(params[3]));
                                if (params[4] != null)
                                    entity.addPart(Stags, new StringBody(params[4]));
                                httpPost.setEntity(entity);
                                response = SonetHttpClient.httpResponse(httpClient, httpPost);
                            } catch (UnsupportedEncodingException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                        return response;
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        // notify photo success
                        String message = getString(response != null ? R.string.success : R.string.failure);
                        Notification notification = new Notification(R.drawable.notification,
                                "photo upload " + message, System.currentTimeMillis());
                        notification.setLatestEventInfo(getBaseContext(), "photo upload", message,
                                PendingIntent.getActivity(PhotoUploadService.this, 0,
                                        (Sonet.getPackageIntent(PhotoUploadService.this, About.class)), 0));
                        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFY_ID,
                                notification);
                        stopSelfResult(mStartId);
                    }

                }).execute(intent.getStringExtra(Accounts.TOKEN), intent.getStringExtra(Statuses.MESSAGE),
                        intent.getStringExtra(Widgets.INSTANT_UPLOAD), place, tags);
            }
        }
    }
}

From source file:com.shafiq.myfeedle.core.PhotoUploadService.java

private void start(Intent intent) {
    if (intent != null) {
        String action = intent.getAction();
        if (Myfeedle.ACTION_UPLOAD.equals(action)) {
            if (intent.hasExtra(Accounts.TOKEN) && intent.hasExtra(Statuses.MESSAGE)
                    && intent.hasExtra(Widgets.INSTANT_UPLOAD)) {
                String place = null;
                if (intent.hasExtra(Splace))
                    place = intent.getStringExtra(Splace);
                String tags = null;
                if (intent.hasExtra(Stags))
                    tags = intent.getStringExtra(Stags);
                // upload a photo
                Notification notification = new Notification(R.drawable.notification, "uploading photo",
                        System.currentTimeMillis());
                notification.setLatestEventInfo(getBaseContext(), "photo upload", "uploading",
                        PendingIntent.getActivity(PhotoUploadService.this, 0,
                                (Myfeedle.getPackageIntent(PhotoUploadService.this, About.class)), 0));
                ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFY_ID,
                        notification);/*from   w ww .j a v  a  2s.  com*/
                (new AsyncTask<String, Void, String>() {

                    @Override
                    protected String doInBackground(String... params) {
                        String response = null;
                        if (params.length > 2) {
                            Log.d(TAG, "upload file: " + params[2]);
                            HttpPost httpPost = new HttpPost(String.format(FACEBOOK_PHOTOS, FACEBOOK_BASE_URL,
                                    Saccess_token, mMyfeedleCrypto.Decrypt(params[0])));
                            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                            File file = new File(params[2]);
                            ContentBody fileBody = new FileBody(file);
                            entity.addPart(Ssource, fileBody);
                            HttpClient httpClient = MyfeedleHttpClient
                                    .getThreadSafeClient(getApplicationContext());
                            try {
                                entity.addPart(Smessage, new StringBody(params[1]));
                                if (params[3] != null)
                                    entity.addPart(Splace, new StringBody(params[3]));
                                if (params[4] != null)
                                    entity.addPart(Stags, new StringBody(params[4]));
                                httpPost.setEntity(entity);
                                response = MyfeedleHttpClient.httpResponse(httpClient, httpPost);
                            } catch (UnsupportedEncodingException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                        return response;
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        // notify photo success
                        String message = getString(response != null ? R.string.success : R.string.failure);
                        Notification notification = new Notification(R.drawable.notification,
                                "photo upload " + message, System.currentTimeMillis());
                        notification.setLatestEventInfo(getBaseContext(), "photo upload", message,
                                PendingIntent.getActivity(PhotoUploadService.this, 0,
                                        (Myfeedle.getPackageIntent(PhotoUploadService.this, About.class)), 0));
                        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFY_ID,
                                notification);
                        stopSelfResult(mStartId);
                    }

                }).execute(intent.getStringExtra(Accounts.TOKEN), intent.getStringExtra(Statuses.MESSAGE),
                        intent.getStringExtra(Widgets.INSTANT_UPLOAD), place, tags);
            }
        }
    }
}

From source file:com.qsoft.components.gallery.utils.GalleryUtils.java

public static <T extends ImageBaseModel> String multiPart(String url, T imageUpload, Long equipmentId,
        Long userId, Long equipmentHistoryId, LocationDTOInterface locationDTOLib) throws IOException {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);//from ww  w.ja  v  a  2  s.  c o  m
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    String result = "";
    if (imageUpload != null) {
        File file = new File(((ImageUploadModel) imageUpload).getRealUri());
        String imageType = getTypeOfImage(((ImageUploadModel) imageUpload).getRealUri()).toUpperCase();
        String imageName = ConstantImage.IMAGE_NAME;
        Gson gson = new Gson();
        String json = gson.toJson(locationDTOLib);
        mpEntity = addParamsForUpload(file, imageType, imageName, equipmentId, userId, json,
                equipmentHistoryId);

        httppost.setEntity(mpEntity);
        HttpResponse response;
        response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            result = GalleryUtils.convertStreamToString(instream);
            instream.close();
        }
    }
    return result;
    //        if (imageUploads != null && imageUploads.size() != 0)
    //        {
    ////            for (T imageUpload : imageUploads)
    ////            {
    ////                File file = new File(((ImageUploadModel) imageUpload).getRealUri());
    ////                mpEntity.addPart(ConstantImage.IMAGE_FILE + imageUploads.indexOf(imageUpload), new FileBody(file));
    ////                mpEntity.addPart(ConstantImage.IMAGE_TYPE + imageUploads.indexOf(imageUpload), new StringBody(getTypeOfImage(((ImageUploadModel) imageUpload).getRealUri()).toUpperCase()));
    ////                mpEntity.addPart(ConstantImage.IMAGE_NAME + imageUploads.indexOf(imageUpload), new StringBody(ConstantImage.IMAGE_NAME + imageUploads.indexOf(imageUpload)));
    ////            }
    ////            mpEntity.addPart(ConstantImage.EQUIPMENT_ID, new StringBody(equipmentId.toString()));
    ////            mpEntity.addPart(ConstantImage.USER_ID, new StringBody(userId.toString()));
    ////            LocationDTOLib locationDTOLib = new LocationDTOLib();
    ////            locationDTOLib.setLatitude(BigDecimal.valueOf(0));
    ////            locationDTOLib.setLongitude(BigDecimal.valueOf(0));
    ////            locationDTOLib.setStreet("Street");
    ////            Gson gson = new Gson();
    ////            String json = gson.toJson(locationDTOLib);
    ////            mpEntity.addPart(ConstantImage.IMAGE_LOCATION_DTO, new StringBody(json));
    ////        }
    ////        httppost.setEntity(mpEntity);
    ////        HttpResponse response;
    ////        response = httpclient.execute(httppost);
    ////        HttpEntity entity = response.getEntity();
    ////        String result = "";
    ////        if (entity != null)
    ////        {
    ////            InputStream instream = entity.getContent();
    ////            result = GalleryUtils.convertStreamToString(instream);
    ////            instream.close();
    ////        }
    //
}

From source file:ee.ioc.phon.netspeechapi.AudioUploader.java

public MultipartEntity createMultipartEntity(FileBody fileBody, String mimeType, int sampleRate) {
    // see: http://stackoverflow.com/questions/3014633
    //MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);

    try {//from www  .j  av  a 2 s  . c o m
        entity.addPart("email", new StringBody(mEmail, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("MODEL_SAMPLE_RATE",
                new StringBody(String.valueOf(sampleRate), "text/plain", Charset.forName("UTF-8")));
        entity.addPart("DECODING", new StringBody(mDecodingSpeed, "text/plain", Charset.forName("UTF-8")));
        String sendEmailAsString = "0";
        if (mIsSendEmail) {
            sendEmailAsString = "1";
        }
        entity.addPart("SEND_EMAIL", new StringBody(sendEmailAsString, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("upload_wav", fileBody);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return entity;
}

From source file:com.grouzen.android.serenity.HttpConnection.java

private HttpResponse post(String url, Bundle params) throws ClientProtocolException, IOException {
    HttpPost method = new HttpPost(url);

    if (params != null) {
        try {/*from   w  w  w  .ja va  2s.  c  o m*/
            if (mMultipartKey != null && mMultipartFileName != null) {
                ByteArrayBody byteArrayBody = new ByteArrayBody(params.getByteArray(mMultipartKey),
                        mMultipartFileName);
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                Charset charset = Charset.forName(CHARSET);

                entity.addPart(mMultipartKey, byteArrayBody);
                params.remove(mMultipartKey);

                for (String k : params.keySet()) {
                    entity.addPart(new FormBodyPart(k, new StringBody(params.getString(k), charset)));
                }

                method.setEntity(entity);
            } else {
                ArrayList<NameValuePair> entity = convertParams(params);

                method.setEntity(new UrlEncodedFormEntity(entity, CHARSET));

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

    return execute(method);
}

From source file:com.impetus.ankush.agent.action.impl.UploadHandler.java

/**
 * Method that builds the multi-part form data request.
 * //from   ww  w. jav a2  s . c  o  m
 * @param urlString
 *            the urlString to which the file needs to be uploaded
 * @param file
 *            the actual file instance that needs to be uploaded
 * @param fileName
 *            name of the file, just to show how to add the usual form
 *            parameters
 * @param fileDescription
 *            some description for the file, just to show how to add the
 *            usual form parameters
 * @return server response as <code>String</code>
 */
public String executeMultiPartRequest(String urlString, File file, String fileName, String fileDescription) {

    HttpPost postRequest = new HttpPost(urlString);
    try {

        MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // The usual form parameters can be added this way
        multiPartEntity.addPart("fileDescription",
                new StringBody(fileDescription != null ? fileDescription : ""));
        multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName()));

        /*
         * Need to construct a FileBody with the file that needs to be
         * attached and specify the mime type of the file. Add the fileBody
         * to the request as an another part. This part will be considered
         * as file part and the rest of them as usual form-data parts
         */
        FileBody fileBody = new FileBody(file, "application/octect-stream");
        multiPartEntity.addPart("file", fileBody);

        postRequest.setEntity(multiPartEntity);

    } catch (Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
        return null;
    }

    return executeRequest(postRequest);
}