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.amalto.workbench.utils.HttpClientUtil.java

private static HttpUriRequest createUploadRequest(String URL, String userName, String localFilename,
        String filename, String imageCatalog, HashMap<String, String> picturePathMap) {
    HttpPost request = new HttpPost(URL);
    MultipartEntity entity = new MultipartEntity();
    if (!Messages.Util_24.equalsIgnoreCase(localFilename)) {
        File file = new File(localFilename);
        if (file.exists()) {
            entity.addPart("imageFile", new FileBody(file)); //$NON-NLS-1$
        }/* w  w w  .  ja v  a2 s  .c  om*/
    }
    if (imageCatalog != null) {
        entity.addPart("catalogName", StringBody.create(imageCatalog, STRING_CONTENT_TYPE, null)); //$NON-NLS-1$
    }
    if (filename != null) {
        int pos = filename.lastIndexOf('.');
        if (pos != -1) {
            filename = filename.substring(0, pos);
        }
        entity.addPart("fileName", StringBody.create(filename, STRING_CONTENT_TYPE, null)); //$NON-NLS-1$
    }
    request.setEntity(entity);
    addStudioToken(request, userName);
    return request;
}

From source file:com.ibuildapp.romanblack.TableReservationPlugin.utils.TableReservationHTTP.java

/**
 * This method sends HTTP request to add order.
 *
 * @param user//from   w ww .  java2  s  . co m
 * @param handler
 * @param orderInfo
 * @return
 */
public static String sendAddOrderRequest(User user, Handler handler, TableReservationInfo orderInfo) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
    HttpConnectionParams.setSoTimeout(httpParameters, 15000);

    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpPost httppost = new HttpPost(ADD_ORDER_URL);
    Log.e(TAG, "ADD_ORDER_URL = " + ADD_ORDER_URL);

    MultipartEntity multipartEntity = new MultipartEntity();

    // user details
    String userType = null;
    String orderUUID = null;
    try {

        if (user.getAccountType() == User.ACCOUNT_TYPES.FACEBOOK) {
            userType = "facebook";
            multipartEntity.addPart("order_customer_name", new StringBody(
                    user.getUserFirstName() + " " + user.getUserLastName(), Charset.forName("UTF-8")));
        } else if (user.getAccountType() == User.ACCOUNT_TYPES.TWITTER) {
            userType = "twitter";
            multipartEntity.addPart("order_customer_name",
                    new StringBody(user.getUserName(), Charset.forName("UTF-8")));
        } else if (user.getAccountType() == User.ACCOUNT_TYPES.IBUILDAPP) {
            userType = "ibuildapp";
            multipartEntity.addPart("order_customer_name",
                    new StringBody(user.getUserName(), Charset.forName("UTF-8")));

        } else if (user.getAccountType() == User.ACCOUNT_TYPES.GUEST) {
            userType = "guest";
            multipartEntity.addPart("order_customer_name", new StringBody("Guest", Charset.forName("UTF-8")));
        }

        multipartEntity.addPart("user_type", new StringBody(userType, Charset.forName("UTF-8")));
        multipartEntity.addPart("user_id", new StringBody(user.getAccountId(), Charset.forName("UTF-8")));
        multipartEntity.addPart("app_id", new StringBody(orderInfo.getAppid(), Charset.forName("UTF-8")));
        multipartEntity.addPart("module_id", new StringBody(orderInfo.getModuleid(), Charset.forName("UTF-8")));

        // order UUID
        orderUUID = UUID.randomUUID().toString();
        multipartEntity.addPart("order_uid", new StringBody(orderUUID, Charset.forName("UTF-8")));

        // order details
        Date tempDate = orderInfo.getOrderDate();
        tempDate.setHours(orderInfo.getOrderTime().houres);
        tempDate.setMinutes(orderInfo.getOrderTime().minutes);
        tempDate.getTimezoneOffset();
        String timeZone = timeZoneToString();

        multipartEntity.addPart("time_zone", new StringBody(timeZone, Charset.forName("UTF-8")));
        multipartEntity.addPart("order_date_time",
                new StringBody(Long.toString(tempDate.getTime() / 1000), Charset.forName("UTF-8")));
        multipartEntity.addPart("order_persons",
                new StringBody(Integer.toString(orderInfo.getPersonsAmount()), Charset.forName("UTF-8")));
        multipartEntity.addPart("order_spec_request",
                new StringBody(orderInfo.getSpecialRequest(), Charset.forName("UTF-8")));
        multipartEntity.addPart("order_customer_phone",
                new StringBody(orderInfo.getPhoneNumber(), Charset.forName("UTF-8")));
        multipartEntity.addPart("order_customer_email",
                new StringBody(orderInfo.getCustomerEmail(), Charset.forName("UTF-8")));

        // add security part
        multipartEntity.addPart("app_id", new StringBody(Statics.appId, Charset.forName("UTF-8")));
        multipartEntity.addPart("token", new StringBody(Statics.appToken, Charset.forName("UTF-8")));

    } catch (Exception e) {
        Log.d("", "");
    }

    httppost.setEntity(multipartEntity);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    try {
        String strResponseSaveGoal = httpclient.execute(httppost, responseHandler);
        Log.d("sendAddOrderRequest", "");
        String res = JSONParser.parseQueryError(strResponseSaveGoal);

        if (res == null || res.length() == 0) {
            return orderUUID;
        } else {
            handler.sendEmptyMessage(ADD_REQUEST_ERROR);
            return null;
        }
    } catch (ConnectTimeoutException conEx) {
        handler.sendEmptyMessage(ADD_REQUEST_ERROR);
        return null;
    } catch (ClientProtocolException ex) {
        handler.sendEmptyMessage(ADD_REQUEST_ERROR);
        return null;
    } catch (IOException ex) {
        handler.sendEmptyMessage(ADD_REQUEST_ERROR);
        return null;
    }
}

From source file:longism.com.api.APIUtils.java

/**
 * TODO Function:Upload file then Load json by type POST.<br>
 *
 * @param activity    - to get context/*from  w  w  w .jav a 2 s  .c  o  m*/
 * @param action      - need authenticate or not, define at top of class
 * @param data        - parameter String
 * @param files       - param file input <key,path of file>
 * @param url         - host of API
 * @param apiCallBack - call back to handle action when start, finish, success or fail
 * @date: July 07, 2015
 * @author: Nguyen Long
 */
public static void loadJSONWithUploadFile(final Activity activity, final int action,
        final HashMap<String, String> data, final HashMap<String, String> files, final String url,
        final String sUserName, final String sUserPassword, final APICallBack apiCallBack) {

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            apiCallBack.uiStart();
        }
    });
    new Thread(new Runnable() {
        @Override
        public synchronized void run() {
            try {
                HttpParams params = new BasicHttpParams();
                HttpConnectionParams.setSoTimeout(params, TIMEOUT_TIME);
                HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_TIME);
                Charset chars = Charset.forName("UTF-8");
                DefaultHttpClient client = new DefaultHttpClient(params);
                HttpPost post = new HttpPost(url);
                //               DLog.e("Accountant", "url  : " + url);
                MultipartEntity multipartEntity = new MultipartEntity();
                if (files != null) {
                    Set<String> set = files.keySet();
                    for (String key : set) {
                        //                     DLog.e("Accountant", "param  : " + key);
                        File file = new File(files.get(key));
                        multipartEntity.addPart(key, new FileBody(file));
                    }
                }
                if (data != null) {
                    Set<String> set = data.keySet();
                    for (String key : set) {
                        //                     DLog.e("Accountant", "param  : " + key);
                        StringBody stringBody = new StringBody(data.get(key), chars);
                        multipartEntity.addPart(key, stringBody);
                    }

                }
                post.setEntity(multipartEntity);
                /**
                 * if need authen then run this code below
                 */
                if (action == ACTION_UPLOAD_WITH_AUTH) {
                    setAuthenticate(client, post, sUserName, sUserPassword);
                }

                HttpResponse response = null;
                response = client.execute(post);
                final StringBuilder builder = new StringBuilder();
                if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                    InputStream inputStream = response.getEntity().getContent();
                    Scanner scanner = new Scanner(inputStream);
                    while (scanner.hasNext()) {
                        builder.append(scanner.nextLine());
                    }
                    inputStream.close();
                    scanner.close();
                    apiCallBack.success(builder.toString(), 0);
                } else {
                    apiCallBack.fail(response != null && response.getStatusLine() != null ? "response null"
                            : "" + response.getStatusLine().getStatusCode());
                }
            } catch (final Exception e) {
                apiCallBack.fail(e.getMessage());
            } finally {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        apiCallBack.uiEnd();
                    }
                });
            }
        }
    }).start();
}

From source file:bluej.collect.DataCollectorImpl.java

public static void debuggerContinue(Project project, String threadName) {
    MultipartEntity mpe = new MultipartEntity();
    mpe.addPart("event[thread_name]", CollectUtility.toBody(threadName));
    submitEvent(project, null, EventName.DEBUGGER_CONTINUE, new PlainEvent(mpe));
}

From source file:bluej.collect.DataCollectorImpl.java

public static void debuggerHalt(Project project, String threadName, SourceLocation[] stack) {
    MultipartEntity mpe = new MultipartEntity();
    mpe.addPart("event[thread_name]", CollectUtility.toBody(threadName));
    submitDebuggerEventWithLocation(project, EventName.DEBUGGER_HALT, mpe, stack);
}

From source file:bluej.collect.DataCollectorImpl.java

public static void debuggerStepInto(Project project, String threadName, SourceLocation[] stack) {
    MultipartEntity mpe = new MultipartEntity();
    mpe.addPart("event[thread_name]", CollectUtility.toBody(threadName));
    submitDebuggerEventWithLocation(project, EventName.DEBUGGER_STEP_INTO, mpe, stack);
}

From source file:bluej.collect.DataCollectorImpl.java

public static void debuggerStepOver(Project project, String threadName, SourceLocation[] stack) {
    MultipartEntity mpe = new MultipartEntity();
    mpe.addPart("event[thread_name]", CollectUtility.toBody(threadName));
    submitDebuggerEventWithLocation(project, EventName.DEBUGGER_STEP_OVER, mpe, stack);
}

From source file:bluej.collect.DataCollectorImpl.java

public static void debuggerHitBreakpoint(Project project, String threadName, SourceLocation[] stack) {
    MultipartEntity mpe = new MultipartEntity();
    mpe.addPart("event[thread_name]", CollectUtility.toBody(threadName));
    submitDebuggerEventWithLocation(project, EventName.DEBUGGER_HIT_BREAKPOINT, mpe, stack);
}

From source file:bluej.collect.DataCollectorImpl.java

public static void codePadSuccess(Package pkg, String command, String output) {
    MultipartEntity mpe = new MultipartEntity();
    mpe.addPart("event[codepad][outcome]", CollectUtility.toBody("success"));
    mpe.addPart("event[codepad][command]", CollectUtility.toBody(command));
    mpe.addPart("event[codepad][result]", CollectUtility.toBody(output));
    submitEvent(pkg.getProject(), pkg, EventName.CODEPAD, new PlainEvent(mpe));
}

From source file:bluej.collect.DataCollectorImpl.java

public static void codePadError(Package pkg, String command, String error) {
    MultipartEntity mpe = new MultipartEntity();
    mpe.addPart("event[codepad][outcome]", CollectUtility.toBody("error"));
    mpe.addPart("event[codepad][command]", CollectUtility.toBody(command));
    mpe.addPart("event[codepad][error]", CollectUtility.toBody(error));
    submitEvent(pkg.getProject(), pkg, EventName.CODEPAD, new PlainEvent(mpe));
}