List of usage examples for com.squareup.okhttp OkHttpClient newCall
public Call newCall(Request request)
From source file:com.evandroid.musica.utils.Net.java
License:Open Source License
public static String getUrlAsString(URL paramURL) throws IOException { Request request = new Request.Builder().header("User-Agent", USER_AGENT).url(paramURL).build(); OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); return response.body().string(); }
From source file:com.example.jordan.sunshine.app.FetchWeatherTask.java
License:Apache License
@Override protected Void doInBackground(String... params) { // If there's no zip code, there's nothing to look up. Verify size of params. if (params.length == 0) { return null; }/*from ww w . j av a 2s . c o m*/ String locationQuery = params[0]; // These two need to be declared outside the try/catch // so that they can be closed in the finally block. // HttpURLConnection urlConnection = null; // BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 14; // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast // Ex URL: http://api.openweathermap.org/data/2.5/forecast/daily?q=92691&mode=json&units=metric&cnt=7 final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0]) .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)).build(); try { URL url = new URL(builtUri.toString()); OkHttpClient client = new OkHttpClient(); //DEV Only - interceptor for Stetho. // TODO remove from release version automatically client.networkInterceptors().add(new StethoInterceptor()); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); if (response != null) { forecastJsonStr = response.body().string(); } } catch (IOException e) { Log.e(LOG_TAG, "Error: ", e); e.printStackTrace(); } if (forecastJsonStr != null) { try { getWeatherDataFromJson(forecastJsonStr, locationQuery); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } } return null; }
From source file:com.example.test.myapplication.TestActivity.java
License:Apache License
private void initDatas() { new Thread(new Runnable() { @Override/*from www .j av a2 s .c o m*/ public void run() { OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder().url("https://www.baidu.com/index.php").build(); Call response = okHttpClient.newCall(request); response.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { Log.i("Response", e.toString()); } @Override public void onResponse(Response response) throws IOException { Log.i("Response", response.body().toString()); mDatas.add(response.toString()); runOnUiThread(new Runnable() { @Override public void run() { mAdapter.notifyDataSetChanged(); } }); } }); } }).start(); }
From source file:com.examples.abelanav2.grpcclient.CloudStorage.java
License:Open Source License
/** * Uploads an image to Google Cloud Storage. * @param url the upload url./*from w ww . j a v a 2 s. co m*/ * @param bitmap the image to upload. * @throws IOException if cannot upload the image. */ public static void uploadImage(String url, Bitmap bitmap) throws IOException { ByteArrayOutputStream bOS = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bOS); byte[] bitmapData = bOS.toByteArray(); InputStream stream = new ByteArrayInputStream(bitmapData); String contentType = URLConnection.guessContentTypeFromStream(stream); InputStreamContent content = new InputStreamContent(contentType, stream); MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg"); OkHttpClient client = new OkHttpClient(); RequestBody requestBody = RequestBodyUtil.create(MEDIA_TYPE_JPEG, content.getInputStream()); Request request = new Request.Builder().url(url).put(requestBody).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } }
From source file:com.facebook.buck.slb.SingleUriServiceTest.java
License:Apache License
@Test public void testClientIsCalledWithFullUrl() throws IOException, InterruptedException { OkHttpClient mockClient = EasyMock.createMock(OkHttpClient.class); String path = "my/super/path"; Request.Builder request = new Request.Builder().url(SERVER + path).get(); Call mockCall = EasyMock.createMock(Call.class); EasyMock.expect(mockClient.newCall(EasyMock.anyObject(Request.class))).andReturn(mockCall); Response response = new Response.Builder().message("my super response").request(request.build()) .protocol(Protocol.HTTP_1_1).code(200).build(); EasyMock.expect(mockCall.execute()).andReturn(response); EasyMock.replay(mockCall, mockClient); try (SingleUriService service = new SingleUriService(SERVER, mockClient)) { service.makeRequest(path, request); }/*from w w w. j a v a 2 s . co m*/ }
From source file:com.facebook.react.bridge.webworkers.WebWorkers.java
License:Open Source License
/** * Utility method used to help develop web workers on debug builds. In release builds, worker * scripts need to be packaged with the app, but in dev mode we want to fetch/reload the worker * script on the fly from the packager. This method fetches the given URL *synchronously* and * writes it to the specified temp file. * * This is exposed from Java only because we don't want to add a C++ networking library dependency * * NB: The caller is responsible for deleting the file specified by outFileName when they're done * with it.//from ww w .j a v a 2 s . c o m * NB: We write to a temp file instead of returning a String because, depending on the size of the * worker script, allocating the full script string on the Java heap can cause an OOM. */ public static void downloadScriptToFileSync(String url, String outFileName) { if (!ReactBuildConfig.DEBUG) { throw new RuntimeException( "For security reasons, downloading scripts is only allowed in debug builds."); } OkHttpClient client = new OkHttpClient(); final File out = new File(outFileName); Request request = new Request.Builder().url(url).build(); try { Response response = client.newCall(request).execute(); Sink output = Okio.sink(out); Okio.buffer(response.body().source()).readAll(output); } catch (IOException e) { throw new RuntimeException("Exception downloading web worker script to file", e); } }
From source file:com.facebook.react.modules.network.NetworkingModuleTest.java
License:Open Source License
@Test public void testGetWithoutHeaders() throws Exception { OkHttpClient httpClient = mock(OkHttpClient.class); when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer<Object>() { @Override//from w w w .j a v a 2 s .c o m 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), "GET", "http://somedomain/foo", 0, JavaOnlyArray.of(), null, true, 0); ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); assertThat(argumentCaptor.getValue().urlString()).isEqualTo("http://somedomain/foo"); // We set the User-Agent header by default assertThat(argumentCaptor.getValue().headers().size()).isEqualTo(1); assertThat(argumentCaptor.getValue().method()).isEqualTo("GET"); }
From source file:com.facebook.react.modules.network.NetworkingModuleTest.java
License:Open Source License
@Test public void testSuccessfulPostRequest() throws Exception { OkHttpClient httpClient = mock(OkHttpClient.class); when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer<Object>() { @Override/* w ww . j av a 2 s . co m*/ public Object answer(InvocationOnMock invocation) throws Throwable { Call callMock = mock(Call.class); return callMock; } }); NetworkingModule networkingModule = new NetworkingModule(null, "", httpClient); JavaOnlyMap body = new JavaOnlyMap(); body.putString("string", "This is request body"); networkingModule.sendRequest(mock(ExecutorToken.class), "POST", "http://somedomain/bar", 0, JavaOnlyArray.of(JavaOnlyArray.of("Content-Type", "text/plain")), body, true, 0); ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); assertThat(argumentCaptor.getValue().urlString()).isEqualTo("http://somedomain/bar"); assertThat(argumentCaptor.getValue().headers().size()).isEqualTo(2); assertThat(argumentCaptor.getValue().method()).isEqualTo("POST"); assertThat(argumentCaptor.getValue().body().contentType().type()).isEqualTo("text"); assertThat(argumentCaptor.getValue().body().contentType().subtype()).isEqualTo("plain"); Buffer contentBuffer = new Buffer(); argumentCaptor.getValue().body().writeTo(contentBuffer); assertThat(contentBuffer.readUtf8()).isEqualTo("This is request body"); }
From source file:com.facebook.react.modules.network.NetworkingModuleTest.java
License:Open Source License
@Test public void testHeaders() throws Exception { OkHttpClient httpClient = mock(OkHttpClient.class); when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer<Object>() { @Override// w w w .j a v a 2s. co m public Object answer(InvocationOnMock invocation) throws Throwable { Call callMock = mock(Call.class); return callMock; } }); NetworkingModule networkingModule = new NetworkingModule(null, "", httpClient); List<JavaOnlyArray> headers = Arrays.asList(JavaOnlyArray.of("Accept", "text/plain"), JavaOnlyArray.of("User-Agent", "React test agent/1.0")); networkingModule.sendRequest(mock(ExecutorToken.class), "GET", "http://someurl/baz", 0, JavaOnlyArray.from(headers), null, true, 0); ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); Headers requestHeaders = argumentCaptor.getValue().headers(); assertThat(requestHeaders.size()).isEqualTo(2); assertThat(requestHeaders.get("Accept")).isEqualTo("text/plain"); assertThat(requestHeaders.get("User-Agent")).isEqualTo("React test agent/1.0"); }
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);/* w w w . j a va 2 s . 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, 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); }