List of usage examples for com.squareup.okhttp MediaType parse
public static MediaType parse(String string)
From source file:com.magnet.max.android.tests.MagnetGsonConverterTest.java
License:Apache License
@SmallTest public void testEnumTypeWithDoubleQuoteUnmarshalling() { Converter magnetGsonConverter = magnetGsonConverterFactory.get(TestEnumType.class); try {/*from w ww. j a va 2 s. co m*/ TestEnumType enumType = (TestEnumType) magnetGsonConverter .fromBody(ResponseBody.create(MediaType.parse("application/json"), "\"ENUM1\"")); assertEquals(TestEnumType.ENUM1, enumType); } catch (IOException e) { e.printStackTrace(); fail(e.getMessage()); } }
From source file:com.magnet.max.android.tests.MagnetGsonConverterTest.java
License:Apache License
@SmallTest public void testEnumListUnmarshalling() { Converter magnetGsonConverter = magnetGsonConverterFactory.get(new TypeToken<ArrayList<TestEnumType>>() { }.getType());//from ww w. j a v a 2 s . c o m try { List<TestEnumType> enums = (List<TestEnumType>) magnetGsonConverter .fromBody(ResponseBody.create(MediaType.parse("application/json"), "[\"ENUM1\",\"ENUM2\"]")); assertEquals(2, enums.size()); assertEquals(TestEnumType.ENUM1, enums.get(0)); assertEquals(TestEnumType.ENUM2, enums.get(1)); } catch (IOException e) { e.printStackTrace(); fail(e.getMessage()); } }
From source file:com.magnet.max.android.tests.MagnetGsonConverterTest.java
License:Apache License
@SmallTest public void testPrimitiveTypeUnmarshalling() { Converter magnetGsonConverter = magnetGsonConverterFactory.get(Integer.class); try {/*w w w. ja v a 2 s . c om*/ Integer intValue = (Integer) magnetGsonConverter .fromBody(ResponseBody.create(MediaType.parse("application/json"), "1")); assertEquals(1, intValue.intValue()); } catch (IOException e) { e.printStackTrace(); fail(e.getMessage()); } }
From source file:com.miz.functions.MizLib.java
License:Apache License
public static Request getJsonPostRequest(String url, JSONObject holder) { return new Request.Builder().url(url).addHeader("Content-type", "application/json") .post(RequestBody.create(MediaType.parse("application/json"), holder.toString())).build(); }
From source file:com.miz.functions.MizLib.java
License:Apache License
public static Request getTraktAuthenticationRequest(String url, String username, String password) throws JSONException { JSONObject holder = new JSONObject(); holder.put("username", username); holder.put("password", password); return new Request.Builder().url(url).addHeader("Content-type", "application/json") .addHeader("trakt-api-key", "43efecdf3f16820856d75c4b4d40d1b1d6d9dd1485dd0edc933d7694ce427178") .addHeader("trakt-api-version", "2").addHeader("trakt-user-login", username) .post(RequestBody.create(MediaType.parse("application/json"), holder.toString())).build(); }
From source file:com.moesif.android.okhttp2.MoesifOkHttp2Stack.java
License:Open Source License
private static RequestBody createRequestBody(Request r) throws AuthFailureError { final byte[] body = r.getBody(); if (body == null) { return RequestBody.create(MediaType.parse(r.getBodyContentType()), ""); }//w w w .ja v a 2s .c o m return RequestBody.create(MediaType.parse(r.getBodyContentType()), body); }
From source file:com.mycelium.lt.api.LtApiClient.java
License:Apache License
private Response getConnectionAndSendRequest(LtRequest request, int timeout) { int originalConnectionIndex = _serverEndpoints.getCurrentEndpointIndex(); // Figure what our current endpoint is. On errors we fail over until we // are back at the initial endpoint HttpEndpoint initialEndpoint = getEndpoint(); while (true) { HttpEndpoint serverEndpoint = _serverEndpoints.getCurrentEndpoint(); try {/* w w w. j ava 2 s .c om*/ OkHttpClient client = serverEndpoint.getClient(); _logger.logInfo("LT connecting to " + serverEndpoint.getBaseUrl() + " (" + _serverEndpoints.getCurrentEndpointIndex() + ")"); // configure TimeOuts client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS); client.setReadTimeout(timeout, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS); Stopwatch callDuration = Stopwatch.createStarted(); // build request final String toSend = getPostBody(request); Request rq = new Request.Builder() .post(RequestBody.create(MediaType.parse("application/json"), toSend)) .url(serverEndpoint.getUri(request.toString()).toString()).build(); // execute request Response response = client.newCall(rq).execute(); callDuration.stop(); _logger.logInfo(String.format("LtApi %s finished (%dms)", request.toString(), callDuration.elapsed(TimeUnit.MILLISECONDS))); // Check for status code 2XX if (response.isSuccessful()) { if (serverEndpoint instanceof FeedbackEndpoint) { ((FeedbackEndpoint) serverEndpoint).onSuccess(); } return response; } else { // If the status code is not 200 we cycle to the next server logError(String.format("Local Trader server request for class %s returned HTTP status code %d", request.getClass().toString(), response.code())); } } catch (IOException e) { logError("getConnectionAndSendRequest failed IO exception."); if (serverEndpoint instanceof FeedbackEndpoint) { _logger.logInfo("Resetting tor"); ((FeedbackEndpoint) serverEndpoint).onError(); } } // We had an IO exception or a bad status, fail over and try again _serverEndpoints.switchToNextEndpoint(); // Check if we are back at the initial endpoint, in which case we have // to give up if (_serverEndpoints.getCurrentEndpointIndex() == originalConnectionIndex) { // We have tried all URLs return null; } } }
From source file:com.mycelium.wapi.api.WapiClient.java
License:Apache License
/** * Attempt to connect and send to a URL in our list of URLS, if it fails try * the next until we have cycled through all URLs. timeout. *///from w w w . j av a 2 s . co m private Response getConnectionAndSendRequestWithTimeout(Object request, String function, int timeout) { int originalConnectionIndex = _serverEndpoints.getCurrentEndpointIndex(); while (true) { // currently active server-endpoint HttpEndpoint serverEndpoint = _serverEndpoints.getCurrentEndpoint(); try { OkHttpClient client = serverEndpoint.getClient(); _logger.logInfo("Connecting to " + serverEndpoint.getBaseUrl() + " (" + _serverEndpoints.getCurrentEndpointIndex() + ")"); // configure TimeOuts client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS); client.setReadTimeout(timeout, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS); Stopwatch callDuration = Stopwatch.createStarted(); // build request final String toSend = getPostBody(request); Request rq = new Request.Builder().addHeader(MYCELIUM_VERSION_HEADER, versionCode) .post(RequestBody.create(MediaType.parse("application/json"), toSend)) .url(serverEndpoint.getUri(WapiConst.WAPI_BASE_PATH, function).toString()).build(); // execute request Response response = client.newCall(rq).execute(); callDuration.stop(); _logger.logInfo(String.format("Wapi %s finished (%dms)", function, callDuration.elapsed(TimeUnit.MILLISECONDS))); // Check for status code 2XX if (response.isSuccessful()) { if (serverEndpoint instanceof FeedbackEndpoint) { ((FeedbackEndpoint) serverEndpoint).onSuccess(); } return response; } else { // If the status code is not 200 we cycle to the next server logError(String.format("Http call to %s failed with %d %s", function, response.code(), response.message())); // throw... } } catch (IOException e) { logError("IOException when sending request " + function, e); if (serverEndpoint instanceof FeedbackEndpoint) { _logger.logInfo("Resetting tor"); ((FeedbackEndpoint) serverEndpoint).onError(); } } // Try the next server _serverEndpoints.switchToNextEndpoint(); if (_serverEndpoints.getCurrentEndpointIndex() == originalConnectionIndex) { // We have tried all URLs return null; } } }
From source file:com.netflix.spinnaker.clouddriver.cloudfoundry.client.HttpCloudFoundryClientTest.java
License:Apache License
@Test void createRetryInterceptorShouldNotRefreshTokenOnBadCredentials() { Request request = new Request.Builder().url("http://duke.of.url").build(); ResponseBody body = ResponseBody.create(MediaType.parse("application/octet-stream"), "Bad credentials"); Response response401 = new Response.Builder().code(401).request(request).body(body).protocol(HTTP_1_1) .build();//from w w w . j a v a2 s. c o m Interceptor.Chain chain = mock(Interceptor.Chain.class); when(chain.request()).thenReturn(request); try { when(chain.proceed(any())).thenReturn(response401); } catch (IOException e) { fail("Should not happen!"); } HttpCloudFoundryClient cloudFoundryClient = new HttpCloudFoundryClient("account", "appsManUri", "metricsUri", "host", "user", "password"); Response response = cloudFoundryClient.createRetryInterceptor(chain); try { verify(chain, times(1)).proceed(eq(request)); } catch (IOException e) { fail("Should not happen!"); } assertThat(response).isEqualTo(response401); }
From source file:com.onaio.steps.helper.UploadFileTask.java
License:Apache License
@Override protected Boolean doInBackground(File... files) { if (!TextUtils.isEmpty(KeyValueStoreFactory.instance(activity).getString(ENDPOINT_URL))) { try {//w ww. j a v a 2 s. c o m OkHttpClient client = new OkHttpClient(); final MediaType MEDIA_TYPE = MediaType.parse("text/csv"); RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("file", files[0].getName(), RequestBody.create(MEDIA_TYPE, files[0])) .build(); Request request = new Request.Builder() .url(KeyValueStoreFactory.instance(activity).getString(ENDPOINT_URL)).post(requestBody) .build(); client.newCall(request).execute(); new CustomNotification().notify(activity, R.string.export_complete, R.string.export_complete_message); return true; } catch (IOException e) { new Logger().log(e, "Export failed."); new CustomNotification().notify(activity, R.string.error_title, R.string.export_failed); } } else { new CustomNotification().notify(activity, R.string.error_title, R.string.export_failed); } return false; }