Example usage for com.squareup.okhttp MultipartBuilder addFormDataPart

List of usage examples for com.squareup.okhttp MultipartBuilder addFormDataPart

Introduction

In this page you can find the example usage for com.squareup.okhttp MultipartBuilder addFormDataPart.

Prototype

public MultipartBuilder addFormDataPart(String name, String filename, RequestBody value) 

Source Link

Document

Add a form data part to the body.

Usage

From source file:com.forateq.cloudcheetah.fragments.AddEmployeeFragment.java

@OnClick(R.id.update_profile)
public void updateProfile() {
    if (isNetworkAvailable()) {
        final ProgressDialog mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setMessage("Adding employee...");
        mProgressDialog.show();//  ww w  .  j a va 2  s.  com
        final SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(ApplicationContext.get());
        String sessionKey = sharedPreferences.getString(AccountGeneral.SESSION_KEY, "");
        String userName = sharedPreferences.getString(AccountGeneral.ACCOUNT_USERNAME, "");
        String deviceid = Settings.Secure.getString(ApplicationContext.get().getContentResolver(),
                Settings.Secure.ANDROID_ID);
        if (isPicChange) {
            MultipartBuilder multipartBuilder = new MultipartBuilder();
            File file = new File(profileImageFileNameTV.getText().toString());
            RequestBody image = RequestBody.create(MediaType.parse("image/jpg"), file);
            multipartBuilder.addFormDataPart("image", file.getName(), image);
            fileRequestBody = multipartBuilder.build();
        } else {
            MultipartBuilder multipartBuilder = new MultipartBuilder();
            multipartBuilder.addFormDataPart("image", "");
            fileRequestBody = multipartBuilder.build();
        }
        Observable<EmployeeResponseWrapper> observable = cloudCheetahAPIService.createEmployee(
                firstNameET.getText().toString(), middleNameET.getText().toString(),
                lastNameET.getText().toString(), genderSP.getSelectedItemPosition(),
                birthDayET.getText().toString(), addressET.getText().toString(), emailET.getText().toString(),
                contactNoET.getText().toString(), 1, titleET.getText().toString(),
                employmentTypeSP.getSelectedItemPosition(), zipCodeET.getText().toString(),
                tinNoET.getText().toString(), sssNoET.getText().toString(),
                driverLicenseNoET.getText().toString(), civilStatusSP.getSelectedItemPosition(),
                notesET.getText().toString(), fileRequestBody, userName, deviceid, sessionKey);
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io()).subscribe(new Subscriber<EmployeeResponseWrapper>() {
                    @Override
                    public void onCompleted() {
                        if (mProgressDialog.isShowing()) {
                            mProgressDialog.dismiss();
                        }
                        MainActivity.popFragment();
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (mProgressDialog.isShowing()) {
                            mProgressDialog.dismiss();
                        }
                        Log.e("AddEmployee", e.getMessage(), e);
                    }

                    @Override
                    public void onNext(EmployeeResponseWrapper employeeResponseWrapper) {
                        if (employeeResponseWrapper.getResponse()
                                .getStatus_code() == AccountGeneral.SUCCESS_CODE) {
                            Log.e("Name", employeeResponseWrapper.getData().getFirst_name());
                            Employees employees = new Employees();
                            employees.setFirst_name(firstNameET.getText().toString());
                            employees.setMiddle_name(middleNameET.getText().toString());
                            employees.setLast_name(lastNameET.getText().toString());
                            employees.setDate_of_birth(birthDayET.getText().toString());
                            employees.setGender_id(genderSP.getSelectedItemPosition());
                            employees.setAddress(addressET.getText().toString());
                            employees.setEmail_address(emailET.getText().toString());
                            employees.setContact_no(contactNoET.getText().toString());
                            employees.setTitle(titleET.getText().toString());
                            employees.setEmployment_type_id(employmentTypeSP.getSelectedItemPosition());
                            employees.setZip_code(zipCodeET.getText().toString());
                            employees.setTin_no(tinNoET.getText().toString());
                            employees.setSss_no(sssNoET.getText().toString());
                            employees.setDrivers_license_no(driverLicenseNoET.getText().toString());
                            employees.setCivil_status_id(civilStatusSP.getSelectedItemPosition());
                            employees.setNotes(notesET.getText().toString());
                            employees.setImage(employeeResponseWrapper.getData().getImage());
                            employees.save();
                            EmployeesFragment.employeesAdapter.addItem(employees);
                            Toast.makeText(getActivity(), "Employee added successfully.", Toast.LENGTH_SHORT)
                                    .show();
                        } else {
                            Toast.makeText(getActivity(),
                                    "There is a adding the employee please try again later.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    } else {
        Toast.makeText(getActivity(), "Please connect to a network to add new employee.", Toast.LENGTH_SHORT)
                .show();
    }

}

From source file:com.forateq.cloudcheetah.fragments.UpdateEmployeeFragment.java

@OnClick(R.id.update_profile)
public void updateProfile() {
    if (isNetworkAvailable()) {
        final ProgressDialog mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setMessage("Updating profile...");
        mProgressDialog.show();// www . j  av a 2s  .c o m
        final SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(ApplicationContext.get());
        String sessionKey = sharedPreferences.getString(AccountGeneral.SESSION_KEY, "");
        String userName = sharedPreferences.getString(AccountGeneral.ACCOUNT_USERNAME, "");
        String deviceid = Settings.Secure.getString(ApplicationContext.get().getContentResolver(),
                Settings.Secure.ANDROID_ID);
        if (isPicChange) {
            MultipartBuilder multipartBuilder = new MultipartBuilder();
            File file = new File(profileImageFileNameTV.getText().toString());
            RequestBody image = RequestBody.create(MediaType.parse("image/jpg"), file);
            multipartBuilder.addFormDataPart("image", file.getName(), image);
            fileRequestBody = multipartBuilder.build();
        } else {
            MultipartBuilder multipartBuilder = new MultipartBuilder();
            multipartBuilder.addFormDataPart("image", "");
            fileRequestBody = multipartBuilder.build();
        }
        Observable<EmployeeResponseWrapper> observable = cloudCheetahAPIService.updateEmployee(employee_id,
                firstNameET.getText().toString(), middleNameET.getText().toString(),
                lastNameET.getText().toString(), genderSP.getSelectedItemPosition(),
                birthDayET.getText().toString(), addressET.getText().toString(), emailET.getText().toString(),
                contactNoET.getText().toString(), 1, titleET.getText().toString(),
                employmentTypeSP.getSelectedItemPosition(), zipCodeET.getText().toString(),
                tinNoET.getText().toString(), sssNoET.getText().toString(),
                driverLicenseNoET.getText().toString(), civilStatusSP.getSelectedItemPosition(),
                notesET.getText().toString(), fileRequestBody, userName, deviceid, sessionKey,
                AccountGeneral.METHOD_PUT);
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io()).subscribe(new Subscriber<EmployeeResponseWrapper>() {
                    @Override
                    public void onCompleted() {
                        if (mProgressDialog.isShowing()) {
                            mProgressDialog.dismiss();
                        }
                        MainActivity.popFragment();
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (mProgressDialog.isShowing()) {
                            mProgressDialog.dismiss();
                        }
                        Log.e("UpdateEmployee", e.getMessage(), e);
                    }

                    @Override
                    public void onNext(EmployeeResponseWrapper employeeResponseWrapper) {
                        if (employeeResponseWrapper.getResponse()
                                .getStatus_code() == AccountGeneral.SUCCESS_CODE) {
                            Log.e("Name", employeeResponseWrapper.getData().getFirst_name());
                            employees.setFirst_name(firstNameET.getText().toString());
                            employees.setMiddle_name(middleNameET.getText().toString());
                            employees.setLast_name(lastNameET.getText().toString());
                            employees.setDate_of_birth(birthDayET.getText().toString());
                            employees.setGender_id(genderSP.getSelectedItemPosition());
                            employees.setAddress(addressET.getText().toString());
                            employees.setEmail_address(emailET.getText().toString());
                            employees.setContact_no(contactNoET.getText().toString());
                            employees.setTitle(titleET.getText().toString());
                            employees.setEmployment_type_id(employmentTypeSP.getSelectedItemPosition());
                            employees.setZip_code(zipCodeET.getText().toString());
                            employees.setTin_no(tinNoET.getText().toString());
                            employees.setSss_no(sssNoET.getText().toString());
                            employees.setDrivers_license_no(driverLicenseNoET.getText().toString());
                            employees.setCivil_status_id(civilStatusSP.getSelectedItemPosition());
                            employees.setNotes(notesET.getText().toString());
                            employees.setImage(employeeResponseWrapper.getData().getImage());
                            employees.save();
                        } else {
                            Toast.makeText(getActivity(),
                                    "There is a problem updating your profile please try again later.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    } else {
        Toast.makeText(getActivity(), "Please connect to a network to update your profile.", Toast.LENGTH_SHORT)
                .show();
    }

}

From source file:com.forateq.cloudcheetah.fragments.UpdateHREmployeeFragment.java

@OnClick(R.id.ripple_update)
public void update() {
    if (isSave) {
        if (isNetworkAvailable()) {
            final ProgressDialog mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.setMessage("Updating Employee...");
            mProgressDialog.show();/*  w  w  w .j a  v  a2s .c o  m*/
            final SharedPreferences sharedPreferences = PreferenceManager
                    .getDefaultSharedPreferences(ApplicationContext.get());
            String sessionKey = sharedPreferences.getString(AccountGeneral.SESSION_KEY, "");
            String userName = sharedPreferences.getString(AccountGeneral.ACCOUNT_USERNAME, "");
            String deviceid = Settings.Secure.getString(ApplicationContext.get().getContentResolver(),
                    Settings.Secure.ANDROID_ID);
            if (isPicChange) {
                MultipartBuilder multipartBuilder = new MultipartBuilder();
                File file = new File(profileImageFileNameTV.getText().toString());
                RequestBody image = RequestBody.create(MediaType.parse("image/jpg"), file);
                multipartBuilder.addFormDataPart("image", file.getName(), image);
                fileRequestBody = multipartBuilder.build();
            } else {
                MultipartBuilder multipartBuilder = new MultipartBuilder();
                multipartBuilder.addFormDataPart("image", "");
                fileRequestBody = multipartBuilder.build();
            }
            Observable<EmployeeResponseWrapper> observable = cloudCheetahAPIService.updateEmployee(employee_id,
                    firstNameET.getText().toString(), middleNameET.getText().toString(),
                    lastNameET.getText().toString(), genderSP.getSelectedItemPosition(),
                    birthDayET.getText().toString(), addressET.getText().toString(),
                    emailET.getText().toString(), contactNoET.getText().toString(), 1,
                    titleET.getText().toString(), employmentTypeSP.getSelectedItemPosition(),
                    zipCodeET.getText().toString(), tinNoET.getText().toString(), sssNoET.getText().toString(),
                    driverLicenseNoET.getText().toString(), civilStatusSP.getSelectedItemPosition(),
                    notesET.getText().toString(), fileRequestBody, userName, deviceid, sessionKey,
                    AccountGeneral.METHOD_PUT);
            observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                    .unsubscribeOn(Schedulers.io()).subscribe(new Subscriber<EmployeeResponseWrapper>() {
                        @Override
                        public void onCompleted() {
                            if (mProgressDialog.isShowing()) {
                                mProgressDialog.dismiss();
                            }
                            updateSaveIV.setImageResource(R.mipmap.ic_mode_edit_white_24dp);
                            isSave = false;
                            disAbleUpdate();
                            MainActivity.popFragment();
                        }

                        @Override
                        public void onError(Throwable e) {
                            if (mProgressDialog.isShowing()) {
                                mProgressDialog.dismiss();
                            }
                            Log.e("UpdateEmployee", e.getMessage(), e);
                        }

                        @Override
                        public void onNext(EmployeeResponseWrapper employeeResponseWrapper) {
                            if (employeeResponseWrapper.getResponse()
                                    .getStatus_code() == AccountGeneral.SUCCESS_CODE) {
                                Log.e("Name", employeeResponseWrapper.getData().getFirst_name());
                                employees.setFirst_name(firstNameET.getText().toString());
                                employees.setMiddle_name(middleNameET.getText().toString());
                                employees.setLast_name(lastNameET.getText().toString());
                                employees.setDate_of_birth(birthDayET.getText().toString());
                                employees.setGender_id(genderSP.getSelectedItemPosition());
                                employees.setAddress(addressET.getText().toString());
                                employees.setEmail_address(emailET.getText().toString());
                                employees.setContact_no(contactNoET.getText().toString());
                                employees.setTitle(titleET.getText().toString());
                                employees.setEmployment_type_id(employmentTypeSP.getSelectedItemPosition());
                                employees.setZip_code(zipCodeET.getText().toString());
                                employees.setTin_no(tinNoET.getText().toString());
                                employees.setSss_no(sssNoET.getText().toString());
                                employees.setDrivers_license_no(driverLicenseNoET.getText().toString());
                                employees.setCivil_status_id(civilStatusSP.getSelectedItemPosition());
                                employees.setNotes(notesET.getText().toString());
                                employees.setImage(employeeResponseWrapper.getData().getImage());
                                employees.save();
                            } else {
                                Toast.makeText(getActivity(),
                                        "There is a problem updating the employee please try again later.",
                                        Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        } else {
            Toast.makeText(ApplicationContext.get(), "Please connect to a network to update the item.",
                    Toast.LENGTH_SHORT).show();
        }
    } else {
        updateSaveIV.setImageResource(R.mipmap.ic_save_white_24dp);
        isSave = true;
        enableUpdate();
    }
}

From source file:com.ibm.watson.developer_cloud.visual_recognition.v1.VisualRecognition.java

License:Open Source License

public VisualRecognitionImages recognize(final String imageName, final InputStream image,
        final LabelSet labelSet) {
    if (image == null)
        throw new IllegalArgumentException("image cannot be null");

    final RequestBuilder requestBuilder = RequestBuilder.post("/v1/tag/recognize");

    final MultipartBuilder bodyBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
    bodyBuilder.addFormDataPart(IMG_FILE, imageName,
            InputStreamRequestBody.create(HttpMediaType.BINARY_FILE, image));

    if (labelSet != null)
        bodyBuilder.addFormDataPart(LABELS_TO_CHECK, GsonSingleton.getGson().toJson(labelSet));

    requestBuilder.withBody(bodyBuilder.build());

    return executeRequest(requestBuilder.build(), VisualRecognitionImages.class);
}

From source file:com.ibm.watson.developer_cloud.visual_recognition.v2.VisualRecognition.java

License:Open Source License

/**
 * Classifies the image/s against the Classifiers. The response includes a score for a classifier
 * only if the score meets the minimum threshold of 0.5. If no score meets the threshold for an
 * image, no classifiers are returned./*from   w w  w.  ja  v a  2 s  . c  o  m*/
 * 
 * <br>
 * <br>
 * Here is an example of how to classify an InputStream image with an existing classifier:
 * 
 * <pre>
 * VisualRecognition service = new VisualRecognition(&quot;2015-12-02&quot;);
 * service.setUsernameAndPassword(&quot;&lt;username&gt;&quot;, &quot;&lt;password&gt;&quot;);
 * 
 * FileInputStream image = new FileInputStream(&quot;car.png&quot;);
 * VisualClassifier car = new VisualClassifier(&quot;Car&quot;);
 * 
 * VisualClassification result = service.classify(&quot;foo.png&quot;, image, car);
 * System.out.println(result);
 * </pre>
 * 
 * @param filename The file name
 * @param imagesInputStream the image/s input stream to classify
 * @param classifiers the classifiers
 * @return the {@link Classification}
 */
public VisualClassification classify(final String filename, final InputStream imagesInputStream,
        final VisualClassifier... classifiers) {
    Validate.notNull(imagesInputStream, "image cannot be null");
    Validate.notNull(filename, "filename cannot be null");

    MultipartBuilder bodyBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
    bodyBuilder.addFormDataPart(IMAGES_FILE, filename,
            InputStreamRequestBody.create(HttpMediaType.BINARY_FILE, imagesInputStream));

    if (classifiers != null && classifiers.length > 0 && classifiers[0] != null) {
        JsonObject classifierIds = getClassifierIdsAsJson(classifiers);
        bodyBuilder.addFormDataPart(CLASSIFIER_IDS, classifierIds.toString());
    }

    RequestBuilder requestBuilder = RequestBuilder.post(PATH_CLASSIFY).withQuery(VERSION, versionDate)
            .withBody(bodyBuilder.build());

    return executeRequest(requestBuilder.build(), VisualClassification.class);
}

From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java

License:Open Source License

private RequestBody buildParts(BaseRequest request) {

    MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);

    for (PartHolder h : TankHttpUtil.getPartsFromBody(request)) {
        if (h.getFileName() == null) {
            if (h.isContentTypeSet()) {
                multipartBuilder.addFormDataPart(h.getPartName(), null,
                        RequestBody.create(MediaType.parse(request.getContentType()), h.getBody()));
            } else {
                multipartBuilder.addFormDataPart(h.getPartName(), h.getBodyAsString());
            }//from w ww.  java  2 s. c  o  m
        } else {
            if (h.isContentTypeSet()) {
                multipartBuilder.addFormDataPart(h.getPartName(), h.getFileName(),
                        RequestBody.create(MediaType.parse(request.getContentType()), h.getBody()));
            } else {
                multipartBuilder.addFormDataPart(h.getPartName(), h.getFileName(),
                        RequestBody.create(null, h.getBody()));
            }
        }
    }
    return multipartBuilder.build();
}

From source file:com.lidroid.xutils.HttpUtils.java

License:Apache License

@NonNull
private RequestBody buildFileRequestBody(RequestParams params, HashMap<String, ContentBody> fileParams) {
    MultipartBuilder builder = new MultipartBuilder();

    builder = builder.type(MultipartBuilder.FORM);
    for (String fileName : fileParams.keySet()) {
        builder.addFormDataPart(fileName, fileName, RequestBody.create(
                MediaType.parse("application/octet-stream"), ((FileBody) fileParams.get(fileName)).getFile()));
    }/*  w ww.  j a v  a 2 s .  c  om*/

    List<NameValuePair> bodyParams = params.getBodyParams();

    if (bodyParams != null) {
        for (NameValuePair param : params.getBodyParams()) {
            builder.addFormDataPart(param.getName(), param.getValue());
        }
    }

    return builder.build();
}

From source file:com.liferay.mobile.android.http.client.OkHttpClientImpl.java

License:Open Source License

protected RequestBody getUploadBody(Request request) {
    JSONObject body = (JSONObject) request.getBody();
    Object tag = request.getTag();

    MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);

    Iterator<String> it = body.keys();

    while (it.hasNext()) {
        String key = it.next();/* www .  ja v  a 2  s  .com*/
        Object value = body.opt(key);

        if (value instanceof UploadData) {
            UploadData data = (UploadData) value;
            RequestBody requestBody = new InputStreamBody(data, tag);
            builder.addFormDataPart(key, data.getFileName(), requestBody);
        } else {
            builder.addFormDataPart(key, value.toString());
        }
    }

    return builder.build();
}

From source file:com.mcxiaoke.next.http.NextRequest.java

License:Apache License

protected RequestBody getRequestBody() throws IOException {
    if (!supportBody()) {
        return null;
    }/*  w ww.  ja v a2s.  c  o  m*/
    if (body != null) {
        return RequestBody.create(HttpConsts.MEDIA_TYPE_OCTET_STREAM, body);
    }
    RequestBody requestBody;
    if (hasParts()) {
        final MultipartBuilder multipart = new MultipartBuilder();
        for (final BodyPart part : parts()) {
            if (part.getBody() != null) {
                multipart.addFormDataPart(part.getName(), part.getFileName(), part.getBody());
            }
        }
        for (Map.Entry<String, String> entry : form().entrySet()) {
            final String key = entry.getKey();
            final String value = entry.getValue();
            multipart.addFormDataPart(key, value == null ? "" : value);
        }
        requestBody = multipart.type(MultipartBuilder.FORM).build();
    } else if (hasForms()) {
        final FormEncodingBuilder bodyBuilder = new FormEncodingBuilder();
        for (Map.Entry<String, String> entry : form().entrySet()) {
            final String key = entry.getKey();
            final String value = entry.getValue();
            bodyBuilder.add(key, value == null ? "" : value);
        }
        requestBody = bodyBuilder.build();
    } else {
        requestBody = null;
    }
    return requestBody;
}

From source file:org.getlantern.firetweet.extension.streaming.util.OkHttpClientImpl.java

License:Open Source License

private RequestBody getRequestBody(HttpParameter[] params) throws IOException {
    if (params == null)
        return null;
    if (!HttpParameter.containsFile(params)) {
        return RequestBody.create(APPLICATION_FORM_URLENCODED, HttpParameter.encodeParameters(params));
    }//from   w w  w .j  a va2 s . c om
    final MultipartBuilder builder = new MultipartBuilder();
    builder.type(MultipartBuilder.FORM);
    for (final HttpParameter param : params) {
        if (param.isFile()) {
            RequestBody requestBody;
            if (param.hasFileBody()) {
                requestBody = new StreamRequestBody(MediaType.parse(param.getContentType()),
                        param.getFileBody(), true);
            } else {
                requestBody = RequestBody.create(MediaType.parse(param.getContentType()), param.getFile());
            }
            builder.addFormDataPart(param.getName(), param.getFileName(), requestBody);
        } else {
            builder.addFormDataPart(param.getName(), param.getValue());
        }
    }
    return builder.build();
}