Search in sources :

Example 61 with Header

use of retrofit2.http.Header in project Audient by komamj.

the class AudientRepositoryModule method provideOkHttpClient.

@Singleton
@Provides
OkHttpClient provideOkHttpClient(Cache cache, final SharedPreferences sharedPreferences, final Gson gson) {
    final HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
    if (BuildConfig.DEBUG) {
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    }
    return new OkHttpClient.Builder().authenticator(new Authenticator() {

        @Nullable
        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            String refershToken = sharedPreferences.getString(Constants.REFRESH_TOKEN, "");
            Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.AUDIENT_HOST).client(new OkHttpClient.Builder().addInterceptor(logInterceptor).build()).addConverterFactory(GsonConverterFactory.create(gson)).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build();
            AudientApi audientApi = retrofit.create(AudientApi.class);
            audientApi.refreshAccessToken(GRANT_TYPE, refershToken, Constants.CLIENT_ID, Constants.CLIENT_SECRET).subscribeWith(new DisposableSubscriber<Token>() {

                @Override
                public void onNext(Token token) {
                    sharedPreferences.edit().putString(Constants.ACCESS_TOKEN, token.accessToken).commit();
                    sharedPreferences.edit().putString(Constants.REFRESH_TOKEN, token.refreshToken).commit();
                }

                @Override
                public void onError(Throwable t) {
                    LogUtils.e(TAG, "refresh token error :" + t.getMessage());
                    sharedPreferences.edit().putBoolean(Constants.LOGIN_STATUS, false).commit();
                    android.os.Process.killProcess(android.os.Process.myPid());
                }

                @Override
                public void onComplete() {
                }
            });
            return response.request().newBuilder().header("Authorization", "Bearer " + sharedPreferences.getString(Constants.ACCESS_TOKEN, "")).build();
        }
    }).addInterceptor(new TokenInterceptor(sharedPreferences)).addInterceptor(logInterceptor).cache(cache).connectTimeout(15, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS).retryOnConnectionFailure(true).build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) GsonBuilder(com.google.gson.GsonBuilder) Request(okhttp3.Request) Token(com.xinshang.audient.model.entities.Token) IOException(java.io.IOException) DisposableSubscriber(io.reactivex.subscribers.DisposableSubscriber) Response(okhttp3.Response) Retrofit(retrofit2.Retrofit) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Authenticator(okhttp3.Authenticator) Nullable(android.support.annotation.Nullable) Route(okhttp3.Route) TokenInterceptor(com.xinshang.audient.model.helper.TokenInterceptor) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Example 62 with Header

use of retrofit2.http.Header in project pact-jvm by DiUS.

the class PactProviderWithMultipleFragmentsTest method runTestWithPactVerificationsAndDefaultResponseValuesArePresent.

@Test
@PactVerifications({ @PactVerification(value = "test_provider2", fragment = "createFragment2") })
public void runTestWithPactVerificationsAndDefaultResponseValuesArePresent() throws IOException {
    HttpResponse httpResponse = Request.get(mockTestProvider2.getUrl()).addHeader("testreqheader", "testreqheadervalue").execute().returnResponse();
    assertThat(Arrays.stream(httpResponse.getHeaders("testresheader")).map(Header::getValue).collect(Collectors.toList()), is(equalTo(List.of("testresheadervalue"))));
}
Also used : Header(org.apache.hc.core5.http.Header) HttpResponse(org.apache.hc.core5.http.HttpResponse) Test(org.junit.Test) PactVerifications(au.com.dius.pact.consumer.junit.PactVerifications)

Example 63 with Header

use of retrofit2.http.Header in project xDrip by NightscoutFoundation.

the class NightscoutUploader method doRESTtreatmentDownload.

private synchronized boolean doRESTtreatmentDownload(SharedPreferences prefs) {
    final String baseURLSettings = prefs.getString("cloud_storage_api_base", "");
    final ArrayList<String> baseURIs = new ArrayList<>();
    boolean new_data = false;
    Log.d(TAG, "doRESTtreatmentDownload() starting run");
    try {
        for (String baseURLSetting : baseURLSettings.split(" ")) {
            String baseURL = baseURLSetting.trim();
            if (baseURL.isEmpty())
                continue;
            baseURIs.add(baseURL + (baseURL.endsWith("/") ? "" : "/"));
        }
    } catch (Exception e) {
        Log.e(TAG, "Unable to process API Base URL: " + e);
        return false;
    }
    // process a list of base uris
    for (String baseURI : baseURIs) {
        try {
            baseURI = TryResolveName(baseURI);
            int apiVersion = 0;
            URI uri = new URI(baseURI);
            if ((uri.getHost().startsWith("192.168.")) && prefs.getBoolean("skip_lan_uploads_when_no_lan", true) && (!JoH.isLANConnected())) {
                Log.d(TAG, "Skipping Nighscout download from: " + uri.getHost() + " due to no LAN connection");
                continue;
            }
            if (uri.getPath().endsWith("/v1/"))
                apiVersion = 1;
            String baseURL;
            String secret = uri.getUserInfo();
            if ((secret == null || secret.isEmpty()) && apiVersion == 0) {
                baseURL = baseURI;
            } else if ((secret == null || secret.isEmpty())) {
                throw new Exception("Starting with API v1, a pass phase is required");
            } else if (apiVersion > 0) {
                baseURL = baseURI.replaceFirst("//[^@]+@", "//");
            } else {
                throw new Exception("Unexpected baseURI: " + baseURI);
            }
            final Retrofit retrofit = new Retrofit.Builder().baseUrl(baseURL).client(client).build();
            final NightscoutService nightscoutService = retrofit.create(NightscoutService.class);
            final String checkurl = retrofit.baseUrl().url().toString();
            if (!isNightscoutCompatible(checkurl)) {
                Log.e(TAG, "Nightscout version: " + getNightscoutVersion(checkurl) + " on " + checkurl + " is not compatible with the Rest-API download feature!");
                continue;
            }
            if (apiVersion == 1) {
                final String hashedSecret = Hashing.sha1().hashBytes(secret.getBytes(Charsets.UTF_8)).toString();
                final Response<ResponseBody> r;
                if (hashedSecret != null) {
                    // update status if needed
                    doStatusUpdate(nightscoutService, retrofit.baseUrl().url().toString(), hashedSecret);
                    // per uri marker
                    final String LAST_MODIFIED_KEY = LAST_SUCCESS_TREATMENT_DOWNLOAD + CipherUtils.getMD5(uri.toString());
                    String last_modified_string = PersistentStore.getString(LAST_MODIFIED_KEY);
                    if (last_modified_string.equals(""))
                        last_modified_string = JoH.getRFC822String(0);
                    final long request_start = JoH.tsl();
                    r = nightscoutService.downloadTreatments(hashedSecret, last_modified_string).execute();
                    if ((r != null) && (r.raw().networkResponse().code() == HttpURLConnection.HTTP_NOT_MODIFIED)) {
                        Log.d(TAG, "Treatments on " + uri.getHost() + ":" + uri.getPort() + " not modified since: " + last_modified_string);
                        // skip further processing of this url
                        continue;
                    }
                    if ((r != null) && (r.isSuccessful())) {
                        last_modified_string = r.raw().header("Last-Modified", JoH.getRFC822String(request_start));
                        final String this_etag = r.raw().header("Etag", "");
                        if (this_etag.length() > 0) {
                            // older versions of nightscout don't support if-modified-since so check the etag for duplication
                            if (this_etag.equals(PersistentStore.getString(ETAG + LAST_MODIFIED_KEY))) {
                                Log.d(TAG, "Skipping Treatments on " + uri.getHost() + ":" + uri.getPort() + " due to etag duplicate: " + this_etag);
                                continue;
                            }
                            PersistentStore.setString(ETAG + LAST_MODIFIED_KEY, this_etag);
                        }
                        final String response = r.body().string();
                        if (d)
                            Log.d(TAG, "Response: " + response);
                        new_data = NightscoutTreatments.processTreatmentResponse(response);
                        PersistentStore.setString(LAST_MODIFIED_KEY, last_modified_string);
                        checkGzipSupport(r);
                    } else {
                        Log.d(TAG, "Failed to get treatments from the base URL");
                    }
                } else {
                    Log.d(TAG, "Old api version not supported");
                }
            }
        } catch (Exception e) {
            String msg = "Unable to do REST API Download " + e + e.getMessage();
            handleRestFailure(msg);
        }
    }
    Log.d(TAG, "doRESTtreatmentDownload() finishing run");
    return new_data;
}
Also used : ArrayList(java.util.ArrayList) URI(java.net.URI) MongoClientURI(com.mongodb.MongoClientURI) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) ResponseBody(okhttp3.ResponseBody) Retrofit(retrofit2.Retrofit)

Example 64 with Header

use of retrofit2.http.Header in project autorest-clientruntime-for-java by Azure.

the class CredentialsTests method tokenCredentialsTest.

@Test
public void tokenCredentialsTest() throws Exception {
    TokenCredentials credentials = new TokenCredentials(null, "this_is_a_token");
    OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
    credentials.applyCredentialsFilter(clientBuilder);
    clientBuilder.addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            String header = chain.request().header("Authorization");
            Assert.assertEquals("Bearer this_is_a_token", header);
            return new Response.Builder().request(chain.request()).code(200).message("OK").protocol(Protocol.HTTP_1_1).body(ResponseBody.create(MediaType.parse("text/plain"), "azure rocks")).build();
        }
    });
    ServiceClient serviceClient = new ServiceClient("http://localhost", clientBuilder, new Retrofit.Builder()) {
    };
    Response response = serviceClient.httpClient().newCall(new Request.Builder().url("http://localhost").build()).execute();
    Assert.assertEquals(200, response.code());
}
Also used : OkHttpClient(okhttp3.OkHttpClient) IOException(java.io.IOException) Response(okhttp3.Response) Retrofit(retrofit2.Retrofit) Interceptor(okhttp3.Interceptor) TokenCredentials(com.microsoft.rest.credentials.TokenCredentials) Test(org.junit.Test)

Example 65 with Header

use of retrofit2.http.Header in project autorest-clientruntime-for-java by Azure.

the class ServiceClientTests method filterTests.

@Test
public void filterTests() throws Exception {
    OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
    Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
    clientBuilder.interceptors().add(0, new FirstFilter());
    clientBuilder.interceptors().add(1, new SecondFilter());
    clientBuilder.interceptors().add(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Assert.assertEquals("1", chain.request().header("filter1"));
            Assert.assertEquals("2", chain.request().header("filter2"));
            return new Response.Builder().request(chain.request()).code(200).message("OK").protocol(Protocol.HTTP_1_1).body(ResponseBody.create(MediaType.parse("text/plain"), "azure rocks")).build();
        }
    });
    ServiceClient serviceClient = new ServiceClient("http://localhost", clientBuilder, retrofitBuilder) {
    };
    Response response = serviceClient.httpClient().newCall(new Request.Builder().url("http://localhost").build()).execute();
    Assert.assertEquals(200, response.code());
}
Also used : OkHttpClient(okhttp3.OkHttpClient) IOException(java.io.IOException) Response(okhttp3.Response) Retrofit(retrofit2.Retrofit) Interceptor(okhttp3.Interceptor) Test(org.junit.Test)

Aggregations

Response (retrofit2.Response)39 ServiceResponse (com.microsoft.rest.ServiceResponse)30 TypeToken (com.google.common.reflect.TypeToken)29 Product (fixtures.lro.models.Product)29 Request (okhttp3.Request)23 Retrofit (retrofit2.Retrofit)21 OkHttpClient (okhttp3.OkHttpClient)19 IOException (java.io.IOException)15 Test (org.junit.Test)14 SubProduct (fixtures.lro.models.SubProduct)12 Interceptor (okhttp3.Interceptor)12 Response (okhttp3.Response)10 ResponseBody (okhttp3.ResponseBody)9 Header (retrofit2.http.Header)6 ArrayList (java.util.ArrayList)4 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)4 GsonBuilder (com.google.gson.GsonBuilder)3 HttpException (retrofit2.HttpException)3 Context (android.content.Context)2 Nullable (android.support.annotation.Nullable)2