Example usage for com.squareup.okhttp MultipartBuilder build

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

Introduction

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

Prototype

public RequestBody build() 

Source Link

Document

Assemble the specified parts into a request body.

Usage

From source file:FunctionalTest.java

License:Apache License

public static void presignedPostPolicy_test() throws Exception {
    println("Test: presignedPostPolicy(PostPolicy policy)");
    String fileName = createFile(3 * MB);
    PostPolicy policy = new PostPolicy(bucketName, fileName, DateTime.now().plusDays(7));
    policy.setContentRange(1 * MB, 4 * MB);
    Map<String, String> formData = client.presignedPostPolicy(policy);

    MultipartBuilder multipartBuilder = new MultipartBuilder();
    multipartBuilder.type(MultipartBuilder.FORM);
    for (Map.Entry<String, String> entry : formData.entrySet()) {
        multipartBuilder.addFormDataPart(entry.getKey(), entry.getValue());
    }/*from  w w  w .  j av  a 2  s. c o m*/
    multipartBuilder.addFormDataPart("file", fileName, RequestBody.create(null, new File(fileName)));

    Request.Builder requestBuilder = new Request.Builder();
    Request request = requestBuilder.url(endpoint + "/" + bucketName).post(multipartBuilder.build()).build();
    OkHttpClient transport = new OkHttpClient();
    Response response = transport.newCall(request).execute();

    if (response != null) {
        if (!response.isSuccessful()) {
            String errorXml = "";

            // read entire body stream to string.
            Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A");
            if (scanner.hasNext()) {
                errorXml = scanner.next();
            }

            println("FAILED", response, errorXml);
        }
    } else {
        println("NO RESPONSE");
    }

    Files.delete(Paths.get(fileName));
    client.removeObject(bucketName, fileName);
}

From source file:abtlibrary.utils.as24ApiClient.ApiClient.java

License:Apache License

/**
 * Build a multipart (file uploading) request body with the given form parameters,
 * which could contain text fields and file fields.
 *
 * @param formParams Form parameters in the form of Map
 * @return RequestBody//from  w w w.  j  a  v  a2  s  .  com
 */
public RequestBody buildRequestBodyMultipart(Map<String, Object> formParams) {
    MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
    for (Entry<String, Object> param : formParams.entrySet()) {
        if (param.getValue() instanceof File) {
            File file = (File) param.getValue();
            Headers partHeaders = Headers.of("Content-Disposition",
                    "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\"");
            MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file));
            mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file));
        } else {
            Headers partHeaders = Headers.of("Content-Disposition",
                    "form-data; name=\"" + param.getKey() + "\"");
            mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue())));
        }
    }
    return mpBuilder.build();
}

From source file:alfio.manager.system.MailgunMailer.java

License:Open Source License

private RequestBody prepareBody(Event event, String to, String subject, String text, Optional<String> html,
        Attachment... attachments) throws IOException {

    String from = event.getDisplayName() + " <" + configurationManager
            .getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), MAILGUN_FROM)) + ">";

    if (ArrayUtils.isEmpty(attachments)) {
        FormEncodingBuilder builder = new FormEncodingBuilder().add("from", from).add("to", to)
                .add("subject", subject).add("text", text);

        String replyTo = configurationManager.getStringConfigValue(
                Configuration.from(event.getOrganizationId(), event.getId(), MAIL_REPLY_TO), "");
        if (StringUtils.isNotBlank(replyTo)) {
            builder.add("h:Reply-To", replyTo);
        }/*  w  w w.j a  v  a  2s. c o m*/
        html.ifPresent((htmlContent) -> builder.add("html", htmlContent));
        return builder.build();

    } else {
        // https://github.com/square/okhttp/blob/parent-2.1.0/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostMultipart.java
        MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);

        multipartBuilder.addFormDataPart("from", from).addFormDataPart("to", to)
                .addFormDataPart("subject", subject).addFormDataPart("text", text);

        html.ifPresent((htmlContent) -> multipartBuilder.addFormDataPart("html", htmlContent));

        for (Attachment attachment : attachments) {
            byte[] data = attachment.getSource();
            multipartBuilder.addFormDataPart("attachment", attachment.getFilename(), RequestBody
                    .create(MediaType.parse(attachment.getContentType()), Arrays.copyOf(data, data.length)));
        }
        return multipartBuilder.build();
    }
}

From source file:cn.finalteam.okhttpfinal.RequestParams.java

License:Apache License

protected RequestBody getRequestBody() {
    RequestBody body = null;/*  www. ja va 2  s. c  o  m*/
    if (jsonBody != null) {
        body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody.toJSONString());
    } else if (requestBody != null) {
        body = requestBody;
    } else if (fileParams.size() > 0) {
        boolean hasData = false;
        MultipartBuilder builder = new MultipartBuilder();
        builder.type(MultipartBuilder.FORM);
        for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
            builder.addFormDataPart(entry.getKey(), entry.getValue());
            hasData = true;
        }

        for (ConcurrentHashMap.Entry<String, FileWrapper> entry : fileParams.entrySet()) {
            FileWrapper file = entry.getValue();
            if (file != null) {
                hasData = true;
                builder.addFormDataPart(entry.getKey(), file.getFileName(),
                        RequestBody.create(file.getMediaType(), file.getFile()));
            }
        }
        if (hasData) {
            body = builder.build();
        }
    } else {
        FormEncodingBuilder builder = new FormEncodingBuilder();
        boolean hasData = false;
        for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
            hasData = true;
        }
        if (hasData) {
            body = builder.build();
        }
    }

    return body;
}

From source file:cn.wochu.wh.net.OkHttpClientManager.java

License:Apache License

private Request buildMultipartFormRequest(String url, File[] files, String[] fileKeys, Param[] params) {
    params = validateParam(params);//from w w w .  j  av  a 2 s.  c om

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

    for (Param param : params) {
        builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""),
                RequestBody.create(null, param.value));
    }
    if (files != null) {
        RequestBody fileBody = null;
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            String fileName = file.getName();
            fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
            //TODO ???contentType
            builder.addPart(
                    Headers.of("Content-Disposition",
                            "form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""),
                    fileBody);
        }
    }

    RequestBody requestBody = builder.build();
    return new Request.Builder().url(url).post(requestBody).build();
}

From source file:com.facebook.react.modules.network.NetworkingModule.java

License:Open Source License

@ReactMethod
public void sendRequest(String method, String url, int requestId, ReadableArray headers, ReadableMap data,
        final Callback callback) {
    // We need to call the callback to avoid leaking memory on JS even when input for sending
    // request is erroneous or insufficient. For non-http based failures we use code 0, which is
    // interpreted as a transport error.
    // Callback accepts following arguments: responseCode, headersString, responseBody

    Request.Builder requestBuilder = new Request.Builder().url(url);

    if (requestId != 0) {
        requestBuilder.tag(requestId);//from www .  ja v  a2  s .  com
    }

    Headers requestHeaders = extractHeaders(headers, data);
    if (requestHeaders == null) {
        callback.invoke(0, null, "Unrecognized headers format");
        return;
    }
    String contentType = requestHeaders.get(CONTENT_TYPE_HEADER_NAME);
    String contentEncoding = requestHeaders.get(CONTENT_ENCODING_HEADER_NAME);
    requestBuilder.headers(requestHeaders);

    if (data == null) {
        requestBuilder.method(method, null);
    } else if (data.hasKey(REQUEST_BODY_KEY_STRING)) {
        if (contentType == null) {
            callback.invoke(0, null, "Payload is set but no content-type header specified");
            return;
        }
        String body = data.getString(REQUEST_BODY_KEY_STRING);
        MediaType contentMediaType = MediaType.parse(contentType);
        if (RequestBodyUtil.isGzipEncoding(contentEncoding)) {
            RequestBody requestBody = RequestBodyUtil.createGzip(contentMediaType, body);
            if (requestBody == null) {
                callback.invoke(0, null, "Failed to gzip request body");
                return;
            }
            requestBuilder.method(method, requestBody);
        } else {
            requestBuilder.method(method, RequestBody.create(contentMediaType, body));
        }
    } else if (data.hasKey(REQUEST_BODY_KEY_URI)) {
        if (contentType == null) {
            callback.invoke(0, null, "Payload is set but no content-type header specified");
            return;
        }
        String uri = data.getString(REQUEST_BODY_KEY_URI);
        InputStream fileInputStream = RequestBodyUtil.getFileInputStream(getReactApplicationContext(), uri);
        if (fileInputStream == null) {
            callback.invoke(0, null, "Could not retrieve file for uri " + uri);
            return;
        }
        requestBuilder.method(method, RequestBodyUtil.create(MediaType.parse(contentType), fileInputStream));
    } else if (data.hasKey(REQUEST_BODY_KEY_FORMDATA)) {
        if (contentType == null) {
            contentType = "multipart/form-data";
        }
        ReadableArray parts = data.getArray(REQUEST_BODY_KEY_FORMDATA);
        MultipartBuilder multipartBuilder = constructMultipartBody(parts, contentType, callback);
        if (multipartBuilder == null) {
            return;
        }
        requestBuilder.method(method, multipartBuilder.build());
    } else {
        // Nothing in data payload, at least nothing we could understand anyway.
        // Ignore and treat it as if it were null.
        requestBuilder.method(method, null);
    }

    mClient.newCall(requestBuilder.build()).enqueue(new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            if (mShuttingDown) {
                return;
            }
            // We need to call the callback to avoid leaking memory on JS even when input for
            // sending request is erronous or insufficient. For non-http based failures we use
            // code 0, which is interpreted as a transport error
            callback.invoke(0, null, e.getMessage());
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (mShuttingDown) {
                return;
            }
            String responseBody;
            try {
                responseBody = response.body().string();
            } catch (IOException e) {
                // The stream has been cancelled or closed, nothing we can do
                callback.invoke(0, null, e.getMessage());
                return;
            }

            WritableMap responseHeaders = Arguments.createMap();
            Headers headers = response.headers();
            for (int i = 0; i < headers.size(); i++) {
                String headerName = headers.name(i);
                // multiple values for the same header
                if (responseHeaders.hasKey(headerName)) {
                    responseHeaders.putString(headerName,
                            responseHeaders.getString(headerName) + ", " + headers.value(i));
                } else {
                    responseHeaders.putString(headerName, headers.value(i));
                }
            }

            callback.invoke(response.code(), responseHeaders, responseBody);
        }
    });
}

From source file:com.facebook.react.modules.network.NetworkingModuleTest.java

License:Open Source License

@Test
public void testMultipartPostRequestBody() throws Exception {
    InputStream inputStream = mock(InputStream.class);
    PowerMockito.mockStatic(RequestBodyUtil.class);
    when(RequestBodyUtil.getFileInputStream(any(ReactContext.class), any(String.class)))
            .thenReturn(inputStream);//from   w w  w.  ja  va2 s .  c  om
    when(RequestBodyUtil.create(any(MediaType.class), any(InputStream.class))).thenCallRealMethod();
    when(inputStream.available()).thenReturn("imageUri".length());

    final MultipartBuilder multipartBuilder = mock(MultipartBuilder.class);
    PowerMockito.whenNew(MultipartBuilder.class).withNoArguments().thenReturn(multipartBuilder);
    when(multipartBuilder.type(any(MediaType.class))).thenAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return multipartBuilder;
        }
    });
    when(multipartBuilder.addPart(any(Headers.class), any(RequestBody.class))).thenAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return multipartBuilder;
        }
    });
    when(multipartBuilder.build()).thenAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return mock(RequestBody.class);
        }
    });

    List<JavaOnlyArray> headers = Arrays.asList(JavaOnlyArray.of("content-type", "multipart/form-data"));

    JavaOnlyMap body = new JavaOnlyMap();
    JavaOnlyArray formData = new JavaOnlyArray();
    body.putArray("formData", formData);

    JavaOnlyMap bodyPart = new JavaOnlyMap();
    bodyPart.putString("string", "locale");
    bodyPart.putArray("headers",
            JavaOnlyArray.from(Arrays.asList(JavaOnlyArray.of("content-disposition", "user"))));
    formData.pushMap(bodyPart);

    JavaOnlyMap imageBodyPart = new JavaOnlyMap();
    imageBodyPart.putString("uri", "imageUri");
    imageBodyPart.putArray("headers",
            JavaOnlyArray.from(Arrays.asList(JavaOnlyArray.of("content-type", "image/jpg"),
                    JavaOnlyArray.of("content-disposition", "filename=photo.jpg"))));
    formData.pushMap(imageBodyPart);

    OkHttpClient httpClient = mock(OkHttpClient.class);
    when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Call callMock = mock(Call.class);
            return callMock;
        }
    });

    NetworkingModule networkingModule = new NetworkingModule(null, "", httpClient);
    networkingModule.sendRequest(mock(ExecutorToken.class), "POST", "http://someurl/uploadFoo", 0,
            JavaOnlyArray.from(headers), body, true, 0);

    // verify RequestBodyPart for image
    PowerMockito.verifyStatic(times(1));
    RequestBodyUtil.getFileInputStream(any(ReactContext.class), eq("imageUri"));
    PowerMockito.verifyStatic(times(1));
    RequestBodyUtil.create(MediaType.parse("image/jpg"), inputStream);

    // verify body
    verify(multipartBuilder).build();
    verify(multipartBuilder).type(MultipartBuilder.FORM);
    ArgumentCaptor<Headers> headersArgumentCaptor = ArgumentCaptor.forClass(Headers.class);
    ArgumentCaptor<RequestBody> bodyArgumentCaptor = ArgumentCaptor.forClass(RequestBody.class);
    verify(multipartBuilder, times(2)).addPart(headersArgumentCaptor.capture(), bodyArgumentCaptor.capture());

    List<Headers> bodyHeaders = headersArgumentCaptor.getAllValues();
    assertThat(bodyHeaders.size()).isEqualTo(2);
    List<RequestBody> bodyRequestBody = bodyArgumentCaptor.getAllValues();
    assertThat(bodyRequestBody.size()).isEqualTo(2);

    assertThat(bodyHeaders.get(0).get("content-disposition")).isEqualTo("user");
    assertThat(bodyRequestBody.get(0).contentType()).isNull();
    assertThat(bodyRequestBody.get(0).contentLength()).isEqualTo("locale".getBytes().length);
    assertThat(bodyHeaders.get(1).get("content-disposition")).isEqualTo("filename=photo.jpg");
    assertThat(bodyRequestBody.get(1).contentType()).isEqualTo(MediaType.parse("image/jpg"));
    assertThat(bodyRequestBody.get(1).contentLength()).isEqualTo("imageUri".getBytes().length);
}

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();/*from  w  ww.  j  av a  2  s  . co  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.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();//from   w  w w .j  a  v  a  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.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();/*from www. ja  va2  s .c  om*/
            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();
    }
}