List of usage examples for com.squareup.okhttp OkHttpClient newCall
public Call newCall(Request request)
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);// w w w . j a v a 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, 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);//from www . j av a 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.felkertech.n.cumulustv.activities.MainActivity.java
public void moreClick() { String[] actions = new String[] { getString(R.string.settings_browse_plugins), getString(R.string.settings_switch_google_drive), getString(R.string.settings_refresh_cloud_local), getString(R.string.settings_view_licenses), getString(R.string.settings_reset_channel_data), getString(R.string.settings_about)/*, getString(R.string.about_mlc)*/ };/* w w w.j a v a2 s .c o m*/ new MaterialDialog.Builder(this).title(R.string.more_actions).items(actions) .itemsCallback(new MaterialDialog.ListCallback() { @Override public void onSelection(MaterialDialog materialDialog, View view, int i, CharSequence charSequence) { switch (i) { case 0: ActivityUtils.browsePlugins(MainActivity.this); break; case 1: ActivityUtils.switchGoogleDrive(MainActivity.this, gapi); break; case 2: ActivityUtils.readDriveData(MainActivity.this, gapi); break; case 3: ActivityUtils.oslClick(MainActivity.this); break; case 4: ActivityUtils.deleteChannelData(MainActivity.this, gapi); break; case 5: ActivityUtils.openAbout(MainActivity.this); break; case 6: new MaterialDialog.Builder(MainActivity.this).title(R.string.about_mlc) .content(R.string.about_mlc_summary).positiveText(R.string.about_mlc_issues) .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { super.onPositive(dialog); Intent gi = new Intent(Intent.ACTION_VIEW); gi.setData(Uri .parse("https://bitbucket.org/fleker/mlc-music-live-channels")); startActivity(gi); } }).show(); case 13: final OkHttpClient client = new OkHttpClient(); new Thread(new Runnable() { @Override public void run() { Request request = new Request.Builder() .url("http://felkerdigitalmedia.com/sampletv.xml").build(); Response response = null; try { response = client.newCall(request).execute(); // Log.d(TAG, response.body().string().substring(0,36)); String s = response.body().string(); List<Program> programs = XMLTVParser.parse(s); /*Log.d(TAG, programs.toString()); Log.d(TAG, "Parsed "+programs.size()); Log.d(TAG, "Program 1: "+ programs.get(0).getTitle());*/ } catch (IOException e) { e.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } } }).start(); break; } } }).show(); }
From source file:com.gezhii.fitgroup.network.OkHttpStack.java
License:Open Source License
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.clone(); //int timeoutMs = request.getTimeoutMs(); int timeoutMs = 30000; Log.i("timeoutMs", timeoutMs); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }//from ww w .j a va 2 s . c o m for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { final String name = responseHeaders.name(i), value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
From source file:com.github.kskelm.baringo.ImageService.java
License:Open Source License
/** * Given an image id and an output stream, download the image * and write it to the stream. It is the caller's responsibility * to close everything.//from w w w.ja v a 2 s .c o m * <p> * NOTE: This is synchronous. * <p> * <b>ACCESS: ANONYMOUS</b> * @param imageLink the image link to download (could be a thumb too) * @param outStream an output stream to write the data to * @return the number of bytes written * @throws IOException could be anything really * @throws BaringoApiException Imgur didn't like something */ public long downloadImage(String imageLink, OutputStream outStream) throws IOException, BaringoApiException { Request request = new Request.Builder().url(imageLink).build(); OkHttpClient client = new OkHttpClient(); com.squareup.okhttp.Response resp = client.newCall(request).execute(); if (resp.code() != 200 || !resp.isSuccessful()) { throw new BaringoApiException(request.urlString() + ": " + resp.message(), resp.code()); } // if if (resp.body() == null) { throw new BaringoApiException("No response body found"); } // if InputStream is = resp.body().byteStream(); BufferedInputStream input = new BufferedInputStream(is); byte[] data = new byte[8192]; // because powers of two are magic long total = 0; int count = 0; while ((count = input.read(data)) != -1) { total += count; outStream.write(data, 0, count); } // while return total; }
From source file:com.github.leonardoxh.temporeal.model.listeners.PushSender.java
License:Apache License
public static void send(String entity) { Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(ApplicationConfiguration.PUSH_SERVICE_URL); requestBuilder//from w w w . jav a2 s. c o m .post(RequestBody.create(MediaType.parse("application/json"), getJsonOfRegistrationsId(entity))); requestBuilder.header("Authorization", ApplicationConfiguration.GCM_PROJECT_ID); OkHttpClient okHttp = new OkHttpClient(); try { Response response = okHttp.newCall(requestBuilder.build()).execute(); System.out.println("Response code: " + response.code()); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.github.mobile.util.HttpImageGetter.java
License:Apache License
@Override public Drawable getDrawable(final String source) { try {/*from w w w . ja v a 2 s . c o m*/ Drawable repositoryImage = requestRepositoryImage(source); if (repositoryImage != null) return repositoryImage; } catch (Exception e) { // Ignore and attempt request over regular HTTP request } if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO) { return loading.getDrawable(source); } try { Request request = new Request.Builder().url(source).build(); OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); Bitmap bitmap = ImageUtils.getBitmap(response.body().bytes(), width, MAX_VALUE); if (bitmap == null) return loading.getDrawable(source); BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap); drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); return drawable; } catch (IOException e) { return loading.getDrawable(source); } }
From source file:com.github.radium226.common.Ok.java
License:Apache License
public static InputStream download(OkHttpClient httpClient, String url) throws IOException { Request request = new Request.Builder().url(url).build(); Response response = httpClient.newCall(request).execute(); InputStream bodyInputStream = response.body().byteStream(); return bodyInputStream; }
From source file:com.google.android.gcm.demo.app.DemoActivity.java
License:Apache License
private boolean registerToUniqush(String registrationId) throws IOException { RequestBody formBody = new FormEncodingBuilder().add("service", "ZenUI_PushService_5") .add("subscriber", "uniqush.client").add("pushservicetype", "gcm").add("regid", registrationId) .build();// w w w . ja v a 2s . com String url = "http://140.128.101.214:9898/subscribe"; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).post(formBody).build(); Response response = client.newCall(request).execute(); return response.isSuccessful(); }
From source file:com.google.android.gcm.demo.app.DemoActivity.java
License:Apache License
private boolean registerToPushd(String registrationId) throws IOException { String host = "http://vps.semoncat.com/push"; RequestBody formBody = new FormEncodingBuilder().add("proto", "gcm").add("token", registrationId) .add("lang", Locale.getDefault().toString()).add("timezone", TimeZone.getDefault().getID()).build(); String url = host + "/subscribers"; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() //.header("Authorization", getAuthHeader("SemonCat", "zoe80904")) .url(url).post(formBody).build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { String id = new Gson().fromJson(response.body().string(), JsonObject.class).get("id").getAsString(); Log.d(TAG, "Id:" + id); //subscriber RequestBody subscriberFormBody = new FormEncodingBuilder().add("ignore_message", "0").build(); String subscriberUrl = host + "/subscriber/%s/subscriptions/zenui_help"; Request subscriberRequest = new Request.Builder() //.header("Authorization", getAuthHeader("SemonCat", "zoe80904")) .url(String.format(subscriberUrl, id)).post(subscriberFormBody).build(); Response subscriberResponse = client.newCall(subscriberRequest).execute(); return subscriberResponse.isSuccessful(); }//from w w w . j a v a2 s.c om return false; }