List of usage examples for com.squareup.okhttp MultipartBuilder FORM
MediaType FORM
To view the source code for com.squareup.okhttp MultipartBuilder FORM.
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 w w w . j a v a 2s. co 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 ww . j a va 2 s.c om */ 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); }// www . j a v a2 s .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;//from w ww .ja v a2s.c om 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 ww w. ja va 2s . com*/ 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();//ww w . j av a 2s . c o m 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.NetworkingModuleTest.java
License:Open Source License
@Test public void testMultipartPostRequestSimple() throws Exception { PowerMockito.mockStatic(RequestBodyUtil.class); when(RequestBodyUtil.getFileInputStream(any(ReactContext.class), any(String.class))) .thenReturn(mock(InputStream.class)); when(RequestBodyUtil.create(any(MediaType.class), any(InputStream.class))) .thenReturn(mock(RequestBody.class)); JavaOnlyMap body = new JavaOnlyMap(); JavaOnlyArray formData = new JavaOnlyArray(); JavaOnlyMap bodyPart = new JavaOnlyMap(); bodyPart.putString("string", "value"); bodyPart.putArray("headers", JavaOnlyArray.from(Arrays.asList(JavaOnlyArray.of("content-disposition", "name")))); formData.pushMap(bodyPart);/*from w ww . ja v a2 s .c o m*/ body.putArray("formData", formData); 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, new JavaOnlyArray(), body, true, 0); // verify url, method, headers ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); assertThat(argumentCaptor.getValue().urlString()).isEqualTo("http://someurl/uploadFoo"); assertThat(argumentCaptor.getValue().method()).isEqualTo("POST"); assertThat(argumentCaptor.getValue().body().contentType().type()).isEqualTo(MultipartBuilder.FORM.type()); assertThat(argumentCaptor.getValue().body().contentType().subtype()) .isEqualTo(MultipartBuilder.FORM.subtype()); Headers requestHeaders = argumentCaptor.getValue().headers(); assertThat(requestHeaders.size()).isEqualTo(1); }
From source file:com.facebook.react.modules.network.NetworkingModuleTest.java
License:Open Source License
@Test public void testMultipartPostRequestHeaders() throws Exception { PowerMockito.mockStatic(RequestBodyUtil.class); when(RequestBodyUtil.getFileInputStream(any(ReactContext.class), any(String.class))) .thenReturn(mock(InputStream.class)); when(RequestBodyUtil.create(any(MediaType.class), any(InputStream.class))) .thenReturn(mock(RequestBody.class)); List<JavaOnlyArray> headers = Arrays.asList(JavaOnlyArray.of("Accept", "text/plain"), JavaOnlyArray.of("User-Agent", "React test agent/1.0"), JavaOnlyArray.of("content-type", "multipart/form-data")); JavaOnlyMap body = new JavaOnlyMap(); JavaOnlyArray formData = new JavaOnlyArray(); JavaOnlyMap bodyPart = new JavaOnlyMap(); bodyPart.putString("string", "value"); bodyPart.putArray("headers", JavaOnlyArray.from(Arrays.asList(JavaOnlyArray.of("content-disposition", "name")))); formData.pushMap(bodyPart);/*from w w w . j ava 2s . c om*/ body.putArray("formData", formData); 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 url, method, headers ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); assertThat(argumentCaptor.getValue().urlString()).isEqualTo("http://someurl/uploadFoo"); assertThat(argumentCaptor.getValue().method()).isEqualTo("POST"); assertThat(argumentCaptor.getValue().body().contentType().type()).isEqualTo(MultipartBuilder.FORM.type()); assertThat(argumentCaptor.getValue().body().contentType().subtype()) .isEqualTo(MultipartBuilder.FORM.subtype()); Headers requestHeaders = argumentCaptor.getValue().headers(); assertThat(requestHeaders.size()).isEqualTo(3); assertThat(requestHeaders.get("Accept")).isEqualTo("text/plain"); assertThat(requestHeaders.get("User-Agent")).isEqualTo("React test agent/1.0"); assertThat(requestHeaders.get("content-type")).isEqualTo("multipart/form-data"); }
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);/* w ww . j a v a2 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.he5ed.lib.cloudprovider.apis.BoxApi.java
License:Apache License
@Override public synchronized CFile uploadFile(@NonNull File file, @Nullable CFolder parent) throws RequestFailException { if (TextUtils.isEmpty(mAccessToken)) { throw new RequestFailException("Access token not available"); }// w ww . j a v a 2 s . c o m // create parameter as json final JSONObject params = new JSONObject(); try { params.put("name", file.getName()); params.put("parent", new JSONObject().put("id", parent != null ? parent.getId() : getRoot().getId())); } catch (JSONException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } // create multipart body MediaType fileType = MediaType.parse(FilesUtils.getFileType(file)); RequestBody multipart = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("attributes", params.toString()) .addFormDataPart("file", file.getName(), RequestBody.create(fileType, file)).build(); Request request = new Request.Builder().url(API_UPLOAD_URL + "/files/content") .header("Authorization", String.format("Bearer %s", mAccessToken)).post(multipart).build(); try { Response response = mHttpClient.newCall(request).execute(); if (response.isSuccessful()) { // new file created JSONObject jsonObject = new JSONObject(response.body().string()); JSONArray entries = jsonObject.getJSONArray("entries"); return buildFile(entries.getJSONObject(0)); } else { throw new RequestFailException(response.message(), response.code()); } } catch (JSONException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } }