List of usage examples for com.squareup.okhttp MediaType parse
public static MediaType parse(String string)
From source file:com.facebook.buck.rules.HttpArtifactCacheTest.java
License:Apache License
private ResponseBody createBody(String contents) throws IOException { return ResponseBody.create(MediaType.parse("application/octet-stream"), createArtifact(contents)); }
From source file:com.facebook.buck.slb.LoadBalancedHttpResponseTest.java
License:Apache License
@Before public void setUp() throws IOException { mockLoadBalancer = createMock(HttpLoadBalancer.class); mockInputStream = createMock(InputStream.class); mockBufferedSource = createMock(BufferedSource.class); mockBufferedSource.close();//from w w w. j av a 2 s.c om EasyMock.expectLastCall().once(); responseBody = ResponseBody.create(MediaType.parse("text/plain"), 42, mockBufferedSource); request = new Request.Builder().url(SERVER.toString()).build(); response = new Response.Builder().body(responseBody).code(200).protocol(Protocol.HTTP_1_1).request(request) .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 ww w . j ava 2 s .co m } 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.NetworkingModule.java
License:Open Source License
private @Nullable MultipartBuilder constructMultipartBody(ReadableArray body, String contentType, Callback callback) {/*from ww w.j a va 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);//from www . j a va 2s . 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.facebook.stetho.okhttp.StethoInterceptorTest.java
License:Open Source License
@Test public void testHappyPath() throws IOException { InOrder inOrder = Mockito.inOrder(mMockEventReporter); hookAlmostRealRequestWillBeSent(mMockEventReporter); ByteArrayOutputStream capturedOutput = hookAlmostRealInterpretResponseStream(mMockEventReporter); Uri requestUri = Uri.parse("http://www.facebook.com/nowhere"); String requestText = "Test input"; Request request = new Request.Builder().url(requestUri.toString()) .method("POST", RequestBody.create(MediaType.parse("text/plain"), requestText)).build(); String originalBodyData = "Success!"; Response reply = new Response.Builder().request(request).protocol(Protocol.HTTP_1_1).code(200) .body(ResponseBody.create(MediaType.parse("text/plain"), originalBodyData)).build(); Response filteredResponse = mInterceptor.intercept(new SimpleTestChain(request, reply, null)); inOrder.verify(mMockEventReporter).isEnabled(); inOrder.verify(mMockEventReporter).requestWillBeSent(any(NetworkEventReporter.InspectorRequest.class)); inOrder.verify(mMockEventReporter).dataSent(anyString(), eq(requestText.length()), eq(requestText.length()));/*from www .j av a 2s . c o m*/ inOrder.verify(mMockEventReporter) .responseHeadersReceived(any(NetworkEventReporter.InspectorResponse.class)); String filteredResponseString = filteredResponse.body().string(); String interceptedOutput = capturedOutput.toString(); inOrder.verify(mMockEventReporter).dataReceived(anyString(), anyInt(), anyInt()); inOrder.verify(mMockEventReporter).responseReadFinished(anyString()); assertEquals(originalBodyData, filteredResponseString); assertEquals(originalBodyData, interceptedOutput); inOrder.verifyNoMoreInteractions(); }
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 va 2 s . co m*/ 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);/*from w w w. j ava 2 s . com*/ 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();/* w w w . java2s . 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 . java 2 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.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(); } }