Example usage for com.squareup.okhttp RequestBody create

List of usage examples for com.squareup.okhttp RequestBody create

Introduction

In this page you can find the example usage for com.squareup.okhttp RequestBody create.

Prototype

public static RequestBody create(final MediaType contentType, final File file) 

Source Link

Document

Returns a new request body that transmits the content of file .

Usage

From source file:com.facebook.stetho.okhttp.StethoInterceptorTest.java

License:Open Source License

@Test
public void testWithRequestCompression() throws IOException {
    AtomicReference<NetworkEventReporter.InspectorRequest> capturedRequest = hookAlmostRealRequestWillBeSent(
            mMockEventReporter);/* w  w  w  .ja  va2s . c  om*/

    MockWebServer server = new MockWebServer();
    server.play();
    server.enqueue(new MockResponse().setBody("Success!"));

    final byte[] decompressed = "Request text".getBytes();
    final byte[] compressed = compress(decompressed);
    assertNotEquals("Bogus test: decompressed and compressed lengths match", compressed.length,
            decompressed.length);

    RequestBody compressedBody = RequestBody.create(MediaType.parse("text/plain"), compress(decompressed));
    Request request = new Request.Builder().url(server.getUrl("/")).addHeader("Content-Encoding", "gzip")
            .post(compressedBody).build();
    Response response = mClientWithInterceptor.newCall(request).execute();

    // Force a read to complete the flow.
    response.body().string();

    assertArrayEquals(decompressed, capturedRequest.get().body());
    Mockito.verify(mMockEventReporter).dataSent(anyString(), eq(decompressed.length), eq(compressed.length));

    server.shutdown();
}

From source file:com.facebook.stetho.okhttp.StethoInterceptorTest.java

License:Open Source License

@Test
public void testWithRequestCompression() throws IOException {
    AtomicReference<NetworkEventReporter.InspectorRequest> capturedRequest = hookAlmostRealRequestWillBeSent(
            mMockEventReporter);/*ww  w .j a  v  a  2s.  c  o m*/

    MockWebServer server = new MockWebServer();
    server.start();
    server.enqueue(new MockResponse().setBody("Success!"));

    final byte[] decompressed = "Request text".getBytes();
    final byte[] compressed = compress(decompressed);
    assertNotEquals("Bogus test: decompressed and compressed lengths match", compressed.length,
            decompressed.length);

    RequestBody compressedBody = RequestBody.create(MediaType.parse("text/plain"), compress(decompressed));
    Request request = new Request.Builder().url(server.getUrl("/")).addHeader("Content-Encoding", "gzip")
            .post(compressedBody).build();
    Response response = mClientWithInterceptor.newCall(request).execute();

    // Force a read to complete the flow.
    response.body().string();

    assertArrayEquals(decompressed, capturedRequest.get().body());
    Mockito.verify(mMockEventReporter).dataSent(anyString(), eq(decompressed.length), eq(compressed.length));

    server.shutdown();
}

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 a  va2s .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.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();/*ww  w.  j  a  va 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();//  ww w  . j a va2s  .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();
    }
}

From source file:com.frostwire.http.HttpClient.java

License:Open Source License

private RequestBody buildReqBody(Request request) {
    if (request.mime() != null && request.body() != null) {
        return RequestBody.create(MediaType.parse(request.mime()), request.body());
    } else {/*  w  w  w  .ja v a 2 s.co  m*/
        return null;
    }
}

From source file:com.frostwire.util.http.OKHTTPClient.java

License:Open Source License

private String post(String url, int timeout, String userAgent, String postContentType, byte[] postData,
        boolean gzip) throws IOException {
    canceled = false;//from   w ww.  java  2s  .c  o m
    final OkHttpClient okHttpClient = newOkHttpClient();
    final Request.Builder builder = prepareRequestBuilder(okHttpClient, url, timeout, userAgent, null, null);
    final RequestBody requestBody = RequestBody.create(MediaType.parse(postContentType), postData);
    prepareOkHttpClientForPost(okHttpClient, gzip);
    builder.post(requestBody);
    return getPostSyncResponse(builder);
}

From source file:com.getchute.android.photopickerplus.callback.ImageDataRequest.java

License:Open Source License

public ImageDataRequest(MediaModel imageData, HttpCallback<ResponseModel<MediaResponseModel>> callback) {
    if (imageData == null) {
        throw new IllegalArgumentException("Need to provide image data");
    }/*from  w  w w.j a va 2  s  .  c o m*/

    setRequestMethod(RequestMethod.POST, RequestBody.create(MediaTypes.JSON, bodyContents(imageData)));
    setUrl(Constants.SELECTED_IMAGES_URL);
    setCallback(callback);
    setParser(new ResponseParser<MediaResponseModel>(MediaResponseModel.class));
}

From source file:com.gezhii.fitgroup.network.OkHttpStack.java

License:Open Source License

private static RequestBody createRequestBody(Request r) throws AuthFailureError {
    byte[] body = r.getBody();
    //        if (body == null) return null;
    if (body == null) {
        body = new byte[0];
    }//from  w w  w.  ja va 2  s.c om

    return RequestBody.create(MediaType.parse(r.getBodyContentType()), body);
}

From source file:com.github.arven.rest.AccountServiceTests.java

@Test
public void registerAccount() throws Exception {
    server = new MockWebServer();
    server.enqueue(new MockResponse().setHeader("Content-Type", JSON)
            .setBody(map.writeValueAsString(new ServiceResponse(ServiceResponse.Type.SUCCESS, 200))));
    server.enqueue(new MockResponse().setHeader("Content-Type", JSON)
            .setBody(map.writeValueAsString(new AccountInformation("trfields", "T. R. Fields"))));
    server.play();/*w w w. j av a2  s.  co  m*/
    URL url = server.getUrl("/users/trfields");

    RequestBody body = RequestBody.create(JSON,
            map.writeValueAsString(new AccountInformation("trfields", "T. R. Fields")));
    Request request1 = new Request.Builder().url(url).put(body).build();
    Response response1 = client.newCall(request1).execute();

    Request request2 = new Request.Builder().url(url).get().build();
    Response response2 = client.newCall(request2).execute();

    RecordedRequest recorded1 = server.takeRequest();
    Assert.assertEquals(map.readTree(recorded1.getUtf8Body()), map.readTree(response2.body().string()));
    Assert.assertEquals(recorded1.getPath(), "/users/trfields");
    Assert.assertEquals(recorded1.getMethod(), "PUT");

    RecordedRequest recorded2 = server.takeRequest();
    Assert.assertEquals(recorded2.getPath(), "/users/trfields");
    Assert.assertEquals(recorded2.getMethod(), "GET");
    server.shutdown();
}