List of usage examples for com.squareup.okhttp Interceptor Interceptor
Interceptor
From source file:org.catrobat.catroid.web.ServerCalls.java
License:Open Source License
public void downloadProject(String url, String filePath, final ResultReceiver receiver, final int notificationId) throws IOException, WebconnectionException { File file = new File(filePath); if (!(file.getParentFile().mkdirs() || file.getParentFile().isDirectory())) { throw new IOException("Directory not created"); }//w w w . ja va2 s. c o m Request request = new Request.Builder().url(url).build(); okHttpClient.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Response originalResponse = chain.proceed(chain.request()); if (notificationId >= oldNotificationId) { oldNotificationId = notificationId; return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), receiver, notificationId)) .build(); } else { return originalResponse; } } }); try { Response response = okHttpClient.newCall(request).execute(); BufferedSink bufferedSink = Okio.buffer(Okio.sink(file)); bufferedSink.writeAll(response.body().source()); bufferedSink.close(); } catch (IOException ioException) { Log.e(TAG, Log.getStackTraceString(ioException)); throw new WebconnectionException(WebconnectionException.ERROR_NETWORK, "Connection could not be established!"); } }
From source file:org.catrobat.catroid.web.ServerCalls.java
License:Open Source License
public void downloadMedia(String url, String filePath, final ResultReceiver receiver) throws IOException, WebconnectionException { File file = new File(filePath); if (!(file.getParentFile().mkdirs() || file.getParentFile().isDirectory())) { throw new IOException("Directory not created"); }// w w w.j ava 2 s.com Request request = new Request.Builder().url(url).build(); okHttpClient.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), receiver, 0)).build(); } }); try { Response response = okHttpClient.newCall(request).execute(); BufferedSink bufferedSink = Okio.buffer(Okio.sink(file)); bufferedSink.writeAll(response.body().source()); bufferedSink.close(); } catch (IOException ioException) { Log.e(TAG, Log.getStackTraceString(ioException)); throw new WebconnectionException(WebconnectionException.ERROR_NETWORK, "Connection could not be established!"); } }
From source file:org.graylog2.rest.RemoteInterfaceProvider.java
License:Open Source License
public <T> T get(Node node, final String authorizationToken, Class<T> interfaceClass) { final OkHttpClient okHttpClient = this.okHttpClient.clone(); okHttpClient.interceptors().add(new Interceptor() { @Override/*from ww w. java 2 s. com*/ public Response intercept(Interceptor.Chain chain) throws IOException { final Request original = chain.request(); Request.Builder builder = original.newBuilder().header("Accept", "application/json") .method(original.method(), original.body()); if (authorizationToken != null) { builder = builder.header("Authorization", authorizationToken); } return chain.proceed(builder.build()); } }); final Retrofit retrofit = new Retrofit.Builder().baseUrl(node.getTransportAddress()) .addConverterFactory(JacksonConverterFactory.create(objectMapper)).client(okHttpClient).build(); return retrofit.create(interfaceClass); }
From source file:org.jboss.arquillian.ce.openshift.HttpClientCreator.java
License:Open Source License
static CeOkHttpClient createHttpClient(final Configuration configuration) { try {/*from w w w . ja va2 s . c om*/ CeOkHttpClient httpClient = new CeOkHttpClient(); // Follow any redirects httpClient.setFollowRedirects(true); httpClient.setFollowSslRedirects(true); KeyManager[] keyManagers = null; // TODO TrustManager[] trustManagers = null; // TODO if (configuration.isTrustCerts()) { httpClient.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String s, SSLSession sslSession) { return true; } }); trustManagers = new TrustManager[] { new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String s) { } public void checkServerTrusted(X509Certificate[] chain, String s) { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }; } SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, new SecureRandom()); httpClient.setSslSocketFactory(sslContext.getSocketFactory()); httpClient.setSslContext(sslContext); // impl detail httpClient.interceptors().add(new Interceptor() { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request authReq = chain.request().newBuilder() .addHeader("Authorization", "Bearer " + configuration.getToken()).build(); return chain.proceed(authReq); } }); httpClient.setConnectTimeout(10, TimeUnit.SECONDS); httpClient.setReadTimeout(10, TimeUnit.SECONDS); OkHttpClientUtils.applyCookieHandler(httpClient); return httpClient; } catch (Exception e) { throw new IllegalStateException(e); } }
From source file:org.mariotaku.twidere.util.OAuthPasswordAuthenticator.java
License:Open Source License
public OAuthPasswordAuthenticator(final TwitterOAuth oauth, final LoginVerificationCallback loginVerificationCallback, final String userAgent) { final RestClient restClient = RestAPIFactory.getRestClient(oauth); this.oauth = oauth; this.client = (OkHttpRestClient) restClient.getRestClient(); final OkHttpClient okhttp = client.getClient(); okhttp.setCookieHandler(new CookieManager()); okhttp.networkInterceptors().add(new Interceptor() { @Override/*from ww w . ja v a2 s .c o m*/ public Response intercept(Chain chain) throws IOException { final Response response = chain.proceed(chain.request()); if (!response.isRedirect()) { return response; } final String location = response.header("Location"); final Response.Builder builder = response.newBuilder(); if (!TextUtils.isEmpty(location) && !endpoint.checkEndpoint(location)) { final HttpUrl originalLocation = HttpUrl .get(URI.create("https://api.twitter.com/").resolve(location)); final HttpUrl.Builder locationBuilder = HttpUrl.parse(endpoint.getUrl()).newBuilder(); for (String pathSegments : originalLocation.pathSegments()) { locationBuilder.addPathSegment(pathSegments); } for (int i = 0, j = originalLocation.querySize(); i < j; i++) { final String name = originalLocation.queryParameterName(i); final String value = originalLocation.queryParameterValue(i); locationBuilder.addQueryParameter(name, value); } final String encodedFragment = originalLocation.encodedFragment(); if (encodedFragment != null) { locationBuilder.encodedFragment(encodedFragment); } final HttpUrl newLocation = locationBuilder.build(); builder.header("Location", newLocation.toString()); } return builder.build(); } }); this.endpoint = restClient.getEndpoint(); this.loginVerificationCallback = loginVerificationCallback; this.userAgent = userAgent; }
From source file:pedroscott.com.popularmoviesapp.rest.RestClientPublic.java
License:Apache License
private OkHttpClient getClient() { OkHttpClient client = new OkHttpClient(); HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); client.interceptors().add(interceptor); client.networkInterceptors().add(new Interceptor() { @Override/* ww w .j a va 2 s. c o m*/ public Response intercept(Chain chain) throws IOException { Request request = chain.request(); HttpUrl url = request.httpUrl().newBuilder().addQueryParameter("api_key", key).build(); request = request.newBuilder().url(url).build(); return chain.proceed(request); } }); client.networkInterceptors().add(new StethoInterceptor()); return client; }
From source file:retrofit.CallTest.java
License:Apache License
@Test public void conversionProblemIncomingMaskedByConverterIsUnwrapped() throws IOException { // MWS has no way to trigger IOExceptions during the response body so use an interceptor. OkHttpClient client = new OkHttpClient(); client.interceptors().add(new Interceptor() { @Override/* w ww . ja v a 2s . c o m*/ public com.squareup.okhttp.Response intercept(Chain chain) throws IOException { com.squareup.okhttp.Response response = chain.proceed(chain.request()); ResponseBody body = response.body(); BufferedSource source = Okio.buffer(new ForwardingSource(body.source()) { @Override public long read(Buffer sink, long byteCount) throws IOException { throw new IOException("cause"); } }); body = ResponseBody.create(body.contentType(), body.contentLength(), source); return response.newBuilder().body(body).build(); } }); Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).client(client) .addConverterFactory(new ToStringConverterFactory() { @Override public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) { return new Converter<ResponseBody, String>() { @Override public String convert(ResponseBody value) throws IOException { try { return value.string(); } catch (IOException e) { // Some serialization libraries mask transport problems in runtime exceptions. Bad! throw new RuntimeException("wrapper", e); } } }; } }).build(); Service example = retrofit.create(Service.class); server.enqueue(new MockResponse().setBody("Hi")); Call<String> call = example.getString(); try { call.execute(); fail(); } catch (IOException e) { assertThat(e).hasMessage("cause"); } }
From source file:retrofit2.CallTest.java
License:Apache License
@Test public void conversionProblemIncomingMaskedByConverterIsUnwrapped() throws IOException { // MWS has no way to trigger IOExceptions during the response body so use an interceptor. OkHttpClient client = new OkHttpClient(); client.interceptors().add(new Interceptor() { @Override/*from ww w. j av a 2s . c o m*/ public com.squareup.okhttp.Response intercept(Chain chain) throws IOException { com.squareup.okhttp.Response response = chain.proceed(chain.request()); ResponseBody body = response.body(); BufferedSource source = Okio.buffer(new ForwardingSource(body.source()) { @Override public long read(Buffer sink, long byteCount) throws IOException { throw new IOException("cause"); } }); body = ResponseBody.create(body.contentType(), body.contentLength(), source); return response.newBuilder().body(body).build(); } }); Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).client(client) .addConverterFactory(new ToStringConverterFactory() { @Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { return new Converter<ResponseBody, String>() { @Override public String convert(ResponseBody value) throws IOException { try { return value.string(); } catch (IOException e) { // Some serialization libraries mask transport problems in runtime exceptions. Bad! throw new RuntimeException("wrapper", e); } } }; } }).build(); Service example = retrofit.create(Service.class); server.enqueue(new MockResponse().setBody("Hi")); Call<String> call = example.getString(); try { call.execute(); fail(); } catch (IOException e) { assertThat(e).hasMessage("cause"); } }