List of usage examples for com.squareup.okhttp OkHttpClient interceptors
List interceptors
To view the source code for com.squareup.okhttp OkHttpClient interceptors.
Click Source Link
From source file:io.macgyver.plugin.atlassian.confluence.BasicConfluenceClient.java
License:Apache License
public BasicConfluenceClient(String url, String username, String password) { OkHttpClient c = new OkHttpClient(); c.interceptors().add(new BasicAuthInterceptor(username, password)); OkRestClient client = new OkRestClient(c); this.target = client.uri(url); // client.getConverterRegistry().setDefaultResponseErrorHandler(new ConfluenceResponseErrorHandler()); }
From source file:io.macgyver.plugin.atlassian.jira.JiraClientImpl.java
License:Apache License
public JiraClientImpl(String url, String username, String password) { OkHttpClient c = new OkHttpClient(); c.interceptors().add(new BasicAuthInterceptor(username, password)); OkRestClient client = new OkRestClient(c); target = client.url(url);/*from w ww . j a va 2s. co m*/ }
From source file:io.macgyver.plugin.elb.a10.A10ClientImpl.java
License:Apache License
protected OkHttpClient getClient() { // not guaranteed to be singleton, but close enough if (clientReference.get() == null) { OkHttpClient c = new OkHttpClient(); c.setConnectTimeout(20, TimeUnit.SECONDS); c.setHostnameVerifier(withoutHostnameVerification()); c.setSslSocketFactory(withoutCertificateValidation().getSocketFactory()); c.setConnectionSpecs(getA10CompatibleConnectionSpecs()); c.interceptors().add(LoggingInterceptor.create(A10ClientImpl.class)); clientReference.set(c);// w ww. j a v a 2s . c o m } return clientReference.get(); }
From source file:io.macgyver.plugin.github.GitHubServiceFactory.java
License:Apache License
@Override protected void doCreateCollaboratorInstances(ServiceRegistry registry, ServiceDefinition primaryDefinition, Object primaryBean) {/*from ww w . j a va 2 s . c o m*/ OkHttpClient c = new OkHttpClient(); GitHub h; final String oauthToken = primaryDefinition.getProperties().getProperty("oauthToken"); final String username = primaryDefinition.getProperties().getProperty("username"); final String password = primaryDefinition.getProperties().getProperty("password"); String url = primaryDefinition.getProperties().getProperty("url"); if (!Strings.isNullOrEmpty(oauthToken)) { logger.info("using oauth"); c.interceptors().add(new BasicAuthInterceptor(oauthToken, "x-oauth-token")); } else if (!Strings.isNullOrEmpty(username)) { logger.info("using username/password auth for OkRest client: " + username + "/" + password); c.interceptors().add(new BasicAuthInterceptor(username, password)); } else { logger.info("using anonymous auth"); } if (Strings.isNullOrEmpty(url)) { url = "https://api.github.com"; } OkRestTarget rest = new OkRestClient(c).url(url); registry.registerCollaborator(primaryDefinition.getName() + "Api", rest); GitHubScannerBuilder scannerBuilder = Kernel.getApplicationContext().getBean(Projector.class) .createBuilder(GitHubScannerBuilder.class); if (!Strings.isNullOrEmpty(url)) { scannerBuilder = scannerBuilder.withUrl(url); } if (!Strings.isNullOrEmpty(username)) { scannerBuilder = scannerBuilder.withUsername(username); } if (!Strings.isNullOrEmpty(password)) { scannerBuilder = scannerBuilder.withPassword(password); } if (!Strings.isNullOrEmpty(oauthToken)) { scannerBuilder = scannerBuilder.withToken(oauthToken); } GitHubScanner scanner = scannerBuilder.build(); registry.registerCollaborator(primaryDefinition.getName() + "Scanner", scanner); }
From source file:mobi.lab.sample_event_logging_library.service.LogPostService.java
License:Open Source License
@Override public void onCreate() { super.onCreate(); //TODO: starting from Android 5.0 we could use JobScheduler (currently not in support libraries) handler = new Handler(); handler.postDelayed(timedRunnable, Config.MAX_TIME_INTERVAL_BETWEEN_REQUESTS); logEventsForRequest = new ArrayList<>(); OkHttpClient client = new OkHttpClient(); client.interceptors().add(new Interceptor() { @Override/*from w w w. j a va 2 s . c o m*/ public com.squareup.okhttp.Response intercept(Chain chain) throws IOException { Request request = chain.request(); Log.d(TAG, String.format("\n\nrequest:%s\nheaders:%s\n" + "url:%s", request.body().toString(), request.headers(), request.httpUrl().toString())); return chain.proceed(request); } }); Retrofit retrofit = new Retrofit.Builder().baseUrl(Network.BASE_API_URL) .addConverterFactory(GsonConverterFactory.create()).client(client).build(); logEventService = retrofit.create(LogEventRequest.class); if (checkCallingOrSelfPermission( Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkCallingOrSelfPermission( Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { //TODO: ask for permission if not given Log.d(TAG, "location permission not granted"); isLocationServicesEnabled = false; return; } isLocationServicesEnabled = true; final LocationManager locationManager = (LocationManager) getApplicationContext() .getSystemService(Context.LOCATION_SERVICE); final Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); Log.d(TAG, "requesting user location"); locationManager.requestLocationUpdates(Config.LOCATION_UPDATES_MIN_TIME, Config.LOCATION_UPDATES_MIN_DISTANCE, criteria, this, null); }
From source file:ninja.poepoe.basewrapper.rest.RestClient.java
License:Open Source License
/** * return Retrofit/*from ww w.j a va 2 s. c om*/ */ public Retrofit RestClient() { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); if (isDebug()) { logging.setLevel(logLevel()); } else { logging.setLevel(Level.NONE); } OkHttpClient client = new OkHttpClient(); client.interceptors().add(logging); client.interceptors().addAll(getInterceptors()); return new Retrofit.Builder().baseUrl(baseURL()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(getFactory()).client(client).build(); }
From source file:objective.taskboard.jira.endpoint.JiraEndpoint.java
License:Open Source License
public <S> S request(Class<S> service, String username, String password) { OkHttpClient client = new OkHttpClient(); client.setReadTimeout(60, TimeUnit.SECONDS); client.setConnectTimeout(60, TimeUnit.SECONDS); client.interceptors().add(new AuthenticationInterceptor(username, password)); client.interceptors().add(new Interceptor() { @Override//from w ww.j a v a 2 s. co m public Response intercept(Chain chain) throws IOException { com.squareup.okhttp.Request request = chain.request(); Response response = chain.proceed(request); int retryCount = 0; while (response.code() == HttpStatus.GATEWAY_TIMEOUT.value() && retryCount < 3) { Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS); response = chain.proceed(request); retryCount++; } if (!response.isSuccessful()) log.error(request.urlString() + " request failed."); return response; } }); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new TaskboardJacksonModule()); objectMapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false); RestAdapter retrofit = new RestAdapter.Builder().setEndpoint(jiraProperties.getUrl()) .setConverter(new JacksonConverter(objectMapper)).setClient(new OkClient(client)).build(); return retrofit.create(service); }
From source file:org.apache.nifi.processors.standard.InvokeHTTP.java
License:Apache License
private void setAuthenticator(OkHttpClient okHttpClient, ProcessContext context) { final String authUser = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_USERNAME).getValue()); final String proxyUsername = trimToEmpty(context.getProperty(PROP_PROXY_USER).getValue()); // If the username/password properties are set then check if digest auth is being used if (!authUser.isEmpty() && "true".equalsIgnoreCase(context.getProperty(PROP_DIGEST_AUTH).getValue())) { final String authPass = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_PASSWORD).getValue()); /*//from www . ja v a 2s .c o m * Currently OkHttp doesn't have built-in Digest Auth Support. The ticket for adding it is here: * https://github.com/square/okhttp/issues/205#issuecomment-154047052 * Once added this should be refactored to use the built in support. For now, a third party lib is needed. */ final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>(); com.burgstaller.okhttp.digest.Credentials credentials = new com.burgstaller.okhttp.digest.Credentials( authUser, authPass); final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(credentials); MultiAuthenticator authenticator = new MultiAuthenticator.Builder().with("Digest", digestAuthenticator) .build(); if (!proxyUsername.isEmpty()) { final String proxyPassword = context.getProperty(PROP_PROXY_PASSWORD).getValue(); authenticator.setProxyUsername(proxyUsername); authenticator.setProxyPassword(proxyPassword); } okHttpClient.interceptors().add(new AuthenticationCacheInterceptor(authCache)); okHttpClient.setAuthenticator(new CachingAuthenticatorDecorator(authenticator, authCache)); } else { // Add proxy authentication only if (!proxyUsername.isEmpty()) { final String proxyPassword = context.getProperty(PROP_PROXY_PASSWORD).getValue(); MultiAuthenticator authenticator = new MultiAuthenticator.Builder().build(); authenticator.setProxyUsername(proxyUsername); authenticator.setProxyPassword(proxyPassword); okHttpClient.setAuthenticator(authenticator); } } }
From source file:org.edx.mobile.discussion.DiscussionAPI.java
License:Open Source License
@Inject public DiscussionAPI(Context context, Config config) { this.context = context; this.config = config; Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create(); OkHttpClient oauthBasedClient = new OkHttpClient(); File cacheDirectory = new File(context.getFilesDir(), "http-cache"); if (!cacheDirectory.exists()) { cacheDirectory.mkdirs();/*from w ww .j a v a 2s .c om*/ } Cache cache = new com.squareup.okhttp.Cache(cacheDirectory, cacheSize); oauthBasedClient.setCache(cache); // oauthBasedClient.interceptors().add(new GzipRequestInterceptor()); oauthBasedClient.interceptors().add(new OauthHeaderRequestInterceptor(context)); oauthBasedClient.interceptors().add(new LoggingInterceptor()); RestAdapter restAdapter = new RestAdapter.Builder().setClient(new OkClient(oauthBasedClient)) .setEndpoint(config.getApiHostURL()).setConverter(new GsonConverter(gson)) // .setRequestInterceptor(new OfflineRequestInterceptor(context, 60)) .setErrorHandler(new RetroHttpExceptionHandler()).setLogLevel(RestAdapter.LogLevel.FULL).build(); discussionService = restAdapter.create(DiscussionService.class); }
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/* w w w . java 2 s.c o m*/ 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); }