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

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

Introduction

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

Prototype

public void addPart(final String name, final ContentBody contentBody) 

Source Link

Usage

From source file:com.android.volley.toolbox.http.HttpClientStack.java

private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request)
        throws IOException, AuthFailureError {

    if (request.containsFile()) {
        /* MultipartEntity multipartEntity = new MultipartEntity();
        final Map<String, MultiPartParam> multipartParams = request.getMultiPartParams();
        for (String key : multipartParams.keySet()) {
        multipartEntity.addPart(new StringPart(key, multipartParams.get(key).value));
        }//www  . java 2s . c  om
                
        final Map<String, File> filesToUpload = request.getFilesToUpload();
        if(filesToUpload!=null){
        for (String key : filesToUpload.keySet()) {
        File file = filesToUpload.get(key) ;
                
        if (file==null || !file.exists()) {
         throw new IOException(String.format("File not found: %s",file.getAbsolutePath()));
        }
                
        if (file.isDirectory()) {
         throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath()));
        }
                
        multipartEntity.addPart(new FilePart(key, file, null, null));
        }
        }
        httpRequest.setEntity(multipartEntity);
        */
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        final Map<String, MultiPartParam> multipartParams = request.getMultiPartParams();
        for (String key : multipartParams.keySet()) {
            multipartEntity.addPart(key,
                    new StringBody(multipartParams.get(key).value, "text/plain", Charset.forName("UTF-8")));
        }

        final Map<String, File> filesToUpload = request.getFilesToUpload();
        if (filesToUpload != null) {
            for (String key : filesToUpload.keySet()) {
                File file = filesToUpload.get(key);

                if (file == null || !file.exists()) {
                    throw new IOException(String.format("File not found: %s", file.getAbsolutePath()));
                }

                if (file.isDirectory()) {
                    throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath()));
                }
                multipartEntity.addPart(key, new FileBody(file));
            }
        }
        httpRequest.setEntity(multipartEntity);

    } else {
        byte[] body = request.getBody();
        if (body != null) {
            HttpEntity entity = new ByteArrayEntity(body);
            httpRequest.setEntity(entity);
        }
    }
}

From source file:outfox.ynote.open.client.YNoteHttpUtils.java

/**
 * Do a http post with the multipart content type. This method is usually
 * used to upload the large size content, such as uploading a file.
 *
 * @param url//  w w  w  . j av a 2s .  com
 * @param formParams
 * @param accessor
 * @return
 * @throws IOException
 * @throws YNoteException
 */
public static HttpResponse doPostByMultipart(String url, Map<String, Object> formParams, OAuthAccessor accessor)
        throws IOException, YNoteException {
    HttpPost post = new HttpPost(url);
    // for multipart encoded post, only sign with the oauth parameters
    // do not sign the our form parameters
    Header oauthHeader = getAuthorizationHeader(url, OAuthMessage.POST, null, accessor);
    if (formParams != null) {
        // encode our ynote parameters
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                Charset.forName("UTF-8"));
        for (Entry<String, Object> parameter : formParams.entrySet()) {
            if (parameter.getValue() instanceof File) {
                // deal with file particular
                entity.addPart(parameter.getKey(), new FileBody((File) parameter.getValue()));
            } else if (parameter.getValue() != null) {
                entity.addPart(parameter.getKey(), new StringBody(parameter.getValue().toString(),
                        Charset.forName(YNoteConstants.ENCODING)));
            }
        }
        post.setEntity(entity);
    }
    post.addHeader(oauthHeader);
    HttpResponse response = client.execute(post);
    if ((response.getStatusLine().getStatusCode() / 100) != 2) {
        YNoteException e = wrapYNoteException(response);
        throw e;
    }
    return response;
}

From source file:cn.dacas.emmclient.security.ssl.SslHttpStack.java

/**
 * If Request is MultiPartRequest type, then set MultipartEntity in the httpRequest object.
 * @param httpRequest//from   www .java  2s.co m
 * @param request
 * @throws AuthFailureError
 */
private static void setMultiPartBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request)
        throws AuthFailureError {

    // Return if Request is not MultiPartRequest
    if (request instanceof MultiPartRequest == false) {
        return;
    }

    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    //Iterate the fileUploads
    Map<String, File> fileUpload = ((MultiPartRequest) request).getFileUploads();
    for (Map.Entry<String, File> entry : fileUpload.entrySet()) {
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        multipartEntity.addPart(((String) entry.getKey()), new FileBody((File) entry.getValue()));
    }

    //Iterate the stringUploads
    Map<String, String> stringUpload = ((MultiPartRequest) request).getStringUploads();
    for (Map.Entry<String, String> entry : stringUpload.entrySet()) {
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        try {
            multipartEntity.addPart(((String) entry.getKey()), new StringBody((String) entry.getValue()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    httpRequest.setEntity(multipartEntity);
}

From source file:com.ring.ytjojo.ssl.SslHttpStack.java

/**
 * If Request is MultiPartRequest type, then set MultipartEntity in the httpRequest object.
 * @param httpRequest/*from  ww w .j  ava  2s.  c o  m*/
 * @param request
 * @throws AuthFailureError
 */
private static void setMultiPartBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request)
        throws AuthFailureError {

    // Return if Request is not MultiPartRequest
    if (request instanceof MultiPartRequest == false) {
        return;
    }

    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    //Iterate the fileUploads
    Map<String, File> fileUpload = ((com.ring.ytjojo.volley.MultiPartRequest) request).getFileUploads();
    for (Map.Entry<String, File> entry : fileUpload.entrySet()) {
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        multipartEntity.addPart(((String) entry.getKey()), new FileBody((File) entry.getValue()));
    }

    //Iterate the stringUploads
    Map<String, String> stringUpload = ((MultiPartRequest) request).getStringUploads();
    for (Map.Entry<String, String> entry : stringUpload.entrySet()) {
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        try {
            multipartEntity.addPart(((String) entry.getKey()), new StringBody((String) entry.getValue()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    httpRequest.setEntity(multipartEntity);
}

From source file:com.amalto.workbench.utils.HttpClientUtil.java

private static HttpUriRequest createUploadFileToServerRequest(String URL, String userName,
        final String fileName) {
    HttpPost request = new HttpPost(URL);
    String path = fileName;//from  w  w  w  .  j  a v a 2  s.  c o m
    if (URL.indexOf("deletefile") == -1) {//$NON-NLS-1$
        if (URL.indexOf("deployjob") != -1) {//$NON-NLS-1$
            path = URL.substring(URL.indexOf("=") + 1);//$NON-NLS-1$
        }
        MultipartEntity entity = new MultipartEntity();
        entity.addPart(path, new FileBody(new File(fileName)));
        request.setEntity(entity);
    }
    addStudioToken(request, userName);
    return request;
}

From source file:com.halseyburgund.roundware.server.RWHttpManager.java

public static String uploadFile(String page, Properties properties, String fileParam, String file)
        throws Exception {
    if (D) {//from  w  ww.ja va2s .c  om
        RWHtmlLog.i(TAG, "Starting upload of file: " + file, null);
    }

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT_MSEC);
    HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT_MSEC);

    HttpClient httpClient = new DefaultHttpClient(httpParams);

    HttpPost request = new HttpPost(page);
    MultipartEntity entity = new MultipartEntity();

    Iterator<Map.Entry<Object, Object>> i = properties.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) i.next();
        String key = (String) entry.getKey();
        String val = (String) entry.getValue();
        entity.addPart(key, new StringBody(val));
        if (D) {
            RWHtmlLog.i(TAG, "Added StringBody multipart for: '" + key + "' = '" + val + "'", null);
        }
    }

    File upload = new File(file);
    entity.addPart(fileParam, new FileBody(upload));
    if (D) {
        String msg = "Added FileBody multipart for: '" + fileParam + "' = <'" + upload.getAbsolutePath()
                + ", size: " + upload.length() + " bytes >'";
        RWHtmlLog.i(TAG, msg, null);
    }

    request.setEntity(entity);

    if (D) {
        RWHtmlLog.i(TAG, "Sending HTTP request...", null);
    }

    HttpResponse response = httpClient.execute(request);

    int st = response.getStatusLine().getStatusCode();

    if (st == HttpStatus.SC_OK) {
        StringBuffer sbResponse = new StringBuffer();
        InputStream content = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = reader.readLine()) != null) {
            sbResponse.append(line);
        }
        content.close(); // this will also close the connection

        if (D) {
            RWHtmlLog.i(TAG, "Upload successful (HTTP code: " + st + ")", null);
            RWHtmlLog.i(TAG, "Server response: " + sbResponse.toString(), null);
        }

        return sbResponse.toString();
    } else {
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        entity.writeTo(ostream);
        RWHtmlLog.e(TAG, "Upload failed (http code: " + st + ")", null);
        RWHtmlLog.e(TAG, "Server response: " + ostream.toString(), null);
        throw new Exception(HTTP_POST_FAILED + st);
    }
}

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

public static String sendPostWithFile(String url, List<NameValuePair> nameValuePairs,
        Map<String, String> fileMap, Context mCtx) {
    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));
    // post.setHeader("Content-Type", "application/x-www-form-urlencoded");
    HttpResponse httpResponse = null;/* ww w .  j  a va 2  s  .c om*/
    // HttpClient httpClient = null;
    post.setHeader("Accept", "*/*");
    try {
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // // ?HTTP request
        for (int index = 0; index < nameValuePairs.size(); index++) {

            entity.addPart(nameValuePairs.get(index).getName(),
                    new StringBody(nameValuePairs.get(index).getValue(), Charset.forName("UTF-8")));

        }
        if (fileMap != null) {
            Iterator iterator = fileMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> entry = (Entry<String, String>) iterator.next();
                File file = new File(entry.getValue());
                entity.addPart(entry.getKey(), new FileBody(file));
            }
        }

        // post.setEntity(new UrlEncodedFormEntity(nameValuePairs,
        // HTTP.UTF_8));

        post.setEntity(entity);
        // ?HTTP response
        // httpClient = getSSLHttpClient();
        httpResponse = httpClient.execute(post);
        // ??200 ok
        int responesCode = httpResponse.getStatusLine().getStatusCode();
        BDebug.d("debug", "responesCode == " + responesCode);
        if (responesCode == 200) {
            // ?
            return EntityUtils.toString(httpResponse.getEntity());
        }

    } catch (ClientProtocolException e) {

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

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

        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.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// www.  j av a 2s .  c  o  m
    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.ibuildapp.romanblack.FanWallPlugin.data.Statics.java

public static FanWallMessage postMessage(String msg, String imagePath, int parentId, int replyId,
        boolean withGps) {
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpClient httpClient = new DefaultHttpClient(params);

    try {/*from   w w  w .  j  av a2s.  c o  m*/
        HttpPost httpPost = new HttpPost(Statics.BASE_URL + "/");

        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart("app_id",
                new StringBody(com.appbuilder.sdk.android.Statics.appId, Charset.forName("UTF-8")));
        multipartEntity.addPart("token",
                new StringBody(com.appbuilder.sdk.android.Statics.appToken, Charset.forName("UTF-8")));
        multipartEntity.addPart("module_id", new StringBody(Statics.MODULE_ID, Charset.forName("UTF-8")));

        // ? ?
        multipartEntity.addPart("parent_id",
                new StringBody(Integer.toString(parentId), Charset.forName("UTF-8")));
        multipartEntity.addPart("reply_id",
                new StringBody(Integer.toString(replyId), Charset.forName("UTF-8")));

        if (Authorization.getAuthorizedUser().getAccountType() == User.ACCOUNT_TYPES.FACEBOOK) {
            multipartEntity.addPart("account_type", new StringBody("facebook", Charset.forName("UTF-8")));
        } else if (Authorization.getAuthorizedUser().getAccountType() == User.ACCOUNT_TYPES.TWITTER) {
            multipartEntity.addPart("account_type", new StringBody("twitter", Charset.forName("UTF-8")));
        } else {
            multipartEntity.addPart("account_type", new StringBody("ibuildapp", Charset.forName("UTF-8")));
        }
        multipartEntity.addPart("account_id",
                new StringBody(Authorization.getAuthorizedUser().getAccountId(), Charset.forName("UTF-8")));
        multipartEntity.addPart("user_name",
                new StringBody(Authorization.getAuthorizedUser().getUserName(), Charset.forName("UTF-8")));
        multipartEntity.addPart("user_avatar",
                new StringBody(Authorization.getAuthorizedUser().getAvatarUrl(), Charset.forName("UTF-8")));

        if (withGps) {
            if (Statics.currentLocation != null) {
                multipartEntity.addPart("latitude",
                        new StringBody(Statics.currentLocation.getLatitude() + "", Charset.forName("UTF-8")));
                multipartEntity.addPart("longitude",
                        new StringBody(Statics.currentLocation.getLongitude() + "", Charset.forName("UTF-8")));
            }
        }

        multipartEntity.addPart("text", new StringBody(msg, Charset.forName("UTF-8")));

        if (!TextUtils.isEmpty(imagePath)) {
            multipartEntity.addPart("images", new FileBody(new File(imagePath)));
        }

        httpPost.setEntity(multipartEntity);

        String resp = httpClient.execute(httpPost, new BasicResponseHandler());

        return JSONParser.parseMessagesString(resp).get(0);

    } catch (Exception e) {
        return null;
    }
}

From source file:eu.geopaparazzi.library.network.NetworkUtilities.java

/**
 * Sends a {@link MultipartEntity} post with text and image files.
 * /*from   w  w  w.j  a  v a 2 s .  co m*/
 * @param url the url to which to POST to.
 * @param user the user or <code>null</code>.
 * @param pwd the password or <code>null</code>.
 * @param stringsMap the {@link HashMap} containing the key and string pairs to send.
 * @param filesMap the {@link HashMap} containing the key and image file paths 
 *                  (jpg, png supported) pairs to send.
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws ClientProtocolException
 */
public static void sentMultiPartPost(String url, String user, String pwd, HashMap<String, String> stringsMap,
        HashMap<String, File> filesMap)
        throws UnsupportedEncodingException, IOException, ClientProtocolException {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost(url);

    if (user != null && pwd != null) {
        String ret = getB64Auth(user, pwd);
        httppost.setHeader("Authorization", ret);
    }

    MultipartEntity mpEntity = new MultipartEntity();
    Set<Entry<String, String>> stringsEntrySet = stringsMap.entrySet();
    for (Entry<String, String> stringEntry : stringsEntrySet) {
        ContentBody cbProperties = new StringBody(stringEntry.getValue());
        mpEntity.addPart(stringEntry.getKey(), cbProperties);
    }

    Set<Entry<String, File>> filesEntrySet = filesMap.entrySet();
    for (Entry<String, File> filesEntry : filesEntrySet) {
        String propName = filesEntry.getKey();
        File file = filesEntry.getValue();
        if (file.exists()) {
            String ext = file.getName().toLowerCase().endsWith("jpg") ? "jpeg" : "png";
            ContentBody cbFile = new FileBody(file, "image/" + ext);
            mpEntity.addPart(propName, cbFile);
        }
    }

    httppost.setEntity(mpEntity);
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
        resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
}