List of usage examples for com.squareup.okhttp MultipartBuilder MultipartBuilder
public MultipartBuilder()
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 a va 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 www. j a va 2s.c o m*/ */ 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); }/*from ww w . jav a 2 s.co 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;//from ww w. j a v a 2 s. com 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);/*w ww.jav a2 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.anony.okhttp.sample.PostMultipart.java
License:Apache License
public void run() throws Exception { // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("title", "Square Logo").addFormDataPart("image", null, RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png"))) .build();//from w ww . j a va 2 s. c om Request request = new Request.Builder().header("Authorization", "Client-ID " + IMGUR_CLIENT_ID) .url("https://api.imgur.com/3/image").post(requestBody).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }
From source file:com.facebook.react.modules.network.NetworkingModule.java
License:Open Source License
private @Nullable MultipartBuilder constructMultipartBody(ReadableArray body, String contentType, Callback callback) {//from w w w . j a v a 2 s .c o m MultipartBuilder multipartBuilder = new MultipartBuilder(); multipartBuilder.type(MediaType.parse(contentType)); for (int i = 0, size = body.size(); i < size; i++) { ReadableMap bodyPart = body.getMap(i); // Determine part's content type. ReadableArray headersArray = bodyPart.getArray("headers"); Headers headers = extractHeaders(headersArray, null); if (headers == null) { callback.invoke(0, null, "Missing or invalid header format for FormData part."); return null; } MediaType partContentType = null; String partContentTypeStr = headers.get(CONTENT_TYPE_HEADER_NAME); if (partContentTypeStr != null) { partContentType = MediaType.parse(partContentTypeStr); // Remove the content-type header because MultipartBuilder gets it explicitly as an // argument and doesn't expect it in the headers array. headers = headers.newBuilder().removeAll(CONTENT_TYPE_HEADER_NAME).build(); } if (bodyPart.hasKey(REQUEST_BODY_KEY_STRING)) { String bodyValue = bodyPart.getString(REQUEST_BODY_KEY_STRING); multipartBuilder.addPart(headers, RequestBody.create(partContentType, bodyValue)); } else if (bodyPart.hasKey(REQUEST_BODY_KEY_URI)) { if (partContentType == null) { callback.invoke(0, null, "Binary FormData part needs a content-type header."); return null; } String fileContentUriStr = bodyPart.getString(REQUEST_BODY_KEY_URI); InputStream fileInputStream = RequestBodyUtil.getFileInputStream(getReactApplicationContext(), fileContentUriStr); if (fileInputStream == null) { callback.invoke(0, null, "Could not retrieve file for uri " + fileContentUriStr); return null; } multipartBuilder.addPart(headers, RequestBodyUtil.create(partContentType, fileInputStream)); } else { callback.invoke(0, null, "Unrecognized FormData part."); } } return multipartBuilder; }
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();/* w ww . ja v a2 s . 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();// www . ja v a 2s . 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.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 ww w . ja v a 2s. 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.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(); } }