List of usage examples for com.squareup.okhttp MultipartBuilder type
MediaType type
To view the source code for com.squareup.okhttp MultipartBuilder type.
Click Source Link
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 ww w . j a va 2 s .c om 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:cn.finalteam.okhttpfinal.RequestParams.java
License:Apache License
protected RequestBody getRequestBody() { RequestBody body = null;/*w w w .j av a 2 s. co 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: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 . jav 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.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);/*www . j a va 2 s . c o m*/ 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.hippo.nimingban.client.ac.ACEngine.java
License:Apache License
public static Call prepareReply(OkHttpClient okHttpClient, ACReplyStruct struct) throws Exception { MultipartBuilder builder = new MultipartBuilder(); builder.type(MultipartBuilder.FORM); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"name\""), RequestBody.create(null, StringUtils.avoidNull(struct.name))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"email\""), RequestBody.create(null, StringUtils.avoidNull(struct.email))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"title\""), RequestBody.create(null, StringUtils.avoidNull(struct.title))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"content\""), RequestBody.create(null, StringUtils.avoidNull(struct.content))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"resto\""), RequestBody.create(null, StringUtils.avoidNull(struct.resto))); if (struct.water) { builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"water\""), RequestBody.create(null, "true")); }//from w ww. ja v a 2 s . c o m InputStreamPipe isPipe = struct.image; if (isPipe != null) { String filename; MediaType mediaType; byte[] bytes; File file = compressBitmap(isPipe, struct.imageType); if (file == null) { String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(struct.imageType); if (TextUtils.isEmpty(extension)) { extension = "jpg"; } filename = "a." + extension; mediaType = MediaType.parse(struct.imageType); if (mediaType == null) { mediaType = MEDIA_TYPE_IMAGE_ALL; } try { isPipe.obtain(); bytes = IOUtils.getAllByte(isPipe.open()); } finally { isPipe.close(); isPipe.release(); } } else { filename = "a.jpg"; mediaType = MEDIA_TYPE_IMAGE_JPEG; InputStream is = null; try { is = new FileInputStream(file); bytes = IOUtils.getAllByte(is); } finally { IOUtils.closeQuietly(is); file.delete(); } } builder.addPart( Headers.of("Content-Disposition", "form-data; name=\"image\"; filename=\"" + filename + "\""), RequestBody.create(mediaType, bytes)); } String url = ACUrl.API_REPLY; Log.d(TAG, url); Request request = new GoodRequestBuilder(url).post(builder.build()).build(); return okHttpClient.newCall(request); }
From source file:com.hippo.nimingban.client.ac.ACEngine.java
License:Apache License
public static Call prepareCreatePost(OkHttpClient okHttpClient, ACPostStruct struct) throws Exception { MultipartBuilder builder = new MultipartBuilder(); builder.type(MultipartBuilder.FORM); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"name\""), RequestBody.create(null, StringUtils.avoidNull(struct.name))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"email\""), RequestBody.create(null, StringUtils.avoidNull(struct.email))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"title\""), RequestBody.create(null, StringUtils.avoidNull(struct.title))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"content\""), RequestBody.create(null, StringUtils.avoidNull(struct.content))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"fid\""), RequestBody.create(null, StringUtils.avoidNull(struct.fid))); if (struct.water) { builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"water\""), RequestBody.create(null, "true")); }/* ww w .j a va2 s .c om*/ InputStreamPipe isPipe = struct.image; if (isPipe != null) { String filename; MediaType mediaType; byte[] bytes; File file = compressBitmap(isPipe, struct.imageType); if (file == null) { String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(struct.imageType); if (TextUtils.isEmpty(extension)) { extension = "jpg"; } filename = "a." + extension; mediaType = MediaType.parse(struct.imageType); if (mediaType == null) { mediaType = MEDIA_TYPE_IMAGE_ALL; } try { isPipe.obtain(); bytes = IOUtils.getAllByte(isPipe.open()); } finally { isPipe.close(); isPipe.release(); } } else { filename = "a.jpg"; mediaType = MEDIA_TYPE_IMAGE_JPEG; InputStream is = null; try { is = new FileInputStream(file); bytes = IOUtils.getAllByte(is); } finally { IOUtils.closeQuietly(is); file.delete(); } } builder.addPart( Headers.of("Content-Disposition", "form-data; name=\"image\"; filename=\"" + filename + "\""), RequestBody.create(mediaType, bytes)); } String url = ACUrl.API_CREATE_POST; Log.d(TAG, url); Request request = new GoodRequestBuilder(url).post(builder.build()).build(); return okHttpClient.newCall(request); }
From source file:com.hkm.root.Tasks.upload_data.java
License:Open Source License
public void OCokHttpUpload(ArrayList<Uri> img_list, final String endpoint, final MediaType typ) throws IOException, Exception { // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image MultipartBuilder mb = new MultipartBuilder(); mb.type(MultipartBuilder.FORM); for (Uri i : img_list) { final File file_location = i.toString().startsWith("file:") ? new File(i.toString().replace("file:///", "")) : new File(Tool.getRealPathFromURI(ac, i)); final RequestBody content_data = RequestBody.create(typ, file_location); final String disposition = String.format(Locale.getDefault(), "form-data; name=\"%s\"; filename=\"%s\"", "target-" + post_target, file_location.getName()); final String disposition_alt = String.format(Locale.getDefault(), "file; filename=\"%s\"", file_location.getName()); mb.addPart(Headers.of("Content-Disposition", disposition_alt, "Content-Transfer-Encoding", "binary"), content_data);/*from w ww.ja v a 2 s . c om*/ } RequestBody requestBody = mb.build(); Request requestBuild = new Request.Builder().url(endpoint + "?pid=" + job_id + "&target=" + post_target) .post(requestBody).tag("post_image").build(); execute_upload(requestBuild); }
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())); }//ww w. j av a2 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.mcxiaoke.next.http.NextRequest.java
License:Apache License
protected RequestBody getRequestBody() throws IOException { if (!supportBody()) { return null; }//from w w w . j a v a 2 s .com 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:com.wialon.remote.OkSdkHttpClient.java
License:Apache License
@Override public void postFile(String url, Map<String, String> params, Callback callback, int timeout, File file) { //Method will work at 2.1 version of library https://github.com/square/okhttp/issues/963 and https://github.com/square/okhttp/pull/969 MultipartBuilder builder = new MultipartBuilder(); builder.type(MultipartBuilder.FORM); RequestBody paramsBody = paramsMapToRequestBody(params); if (paramsBody != null) { builder.addPart(paramsBody);//from ww w . j av a 2s. co m } builder.addPart(RequestBody.create(MediaType.parse(""), file)); Request request = new Request.Builder().url(url).post(builder.build()).build(); threadPool.submit(new HttpRequest(getHttpClient(timeout), request, callback)); }