Search in sources :

Example 31 with Level

use of okhttp3.logging.HttpLoggingInterceptor.Level in project EhViewer by seven332.

the class CookieRepositoryTest method testRemoveByExpired.

@Test
public void testRemoveByExpired() {
    Context app = RuntimeEnvironment.application;
    HttpUrl urlEh = HttpUrl.parse("http://www.ehviewer.com/");
    Cookie cookieEh1 = new Cookie.Builder().name("level").value("999").domain("www.ehviewer.com").path("/").expiresAt(System.currentTimeMillis() + 100000).build();
    Cookie cookieEh2 = new Cookie.Builder().name("level").value("0").domain("www.ehviewer.com").path("/").expiresAt(System.currentTimeMillis() - 100000).build();
    CookieRepository repository = new CookieRepository(app, "cookie.db");
    repository.saveFromResponse(urlEh, Collections.singletonList(cookieEh1));
    repository.saveFromResponse(urlEh, Collections.singletonList(cookieEh2));
    Map<String, CookieSet> map = Reflect.on(repository).field("map").get();
    assertEquals(1, map.size());
    equals(map.get("www.ehviewer.com"), Collections.<Cookie>emptyList());
    repository.close();
    repository = new CookieRepository(app, "cookie.db");
    map = Reflect.on(repository).field("map").get();
    assertEquals(0, map.size());
    repository.close();
}
Also used : Context(android.content.Context) Cookie(okhttp3.Cookie) HttpUrl(okhttp3.HttpUrl) Test(org.junit.Test)

Example 32 with Level

use of okhttp3.logging.HttpLoggingInterceptor.Level in project EhViewer by seven332.

the class CookieRepositoryTest method testRemoveByNonPersistent.

@Test
public void testRemoveByNonPersistent() {
    Context app = RuntimeEnvironment.application;
    HttpUrl urlEh = HttpUrl.parse("http://www.ehviewer.com/");
    Cookie cookieEh1 = new Cookie.Builder().name("level").value("999").domain("www.ehviewer.com").path("/").expiresAt(System.currentTimeMillis() + 100000).build();
    Cookie cookieEh2 = new Cookie.Builder().name("level").value("0").domain("www.ehviewer.com").path("/").build();
    CookieRepository repository = new CookieRepository(app, "cookie.db");
    repository.saveFromResponse(urlEh, Collections.singletonList(cookieEh1));
    repository.saveFromResponse(urlEh, Collections.singletonList(cookieEh2));
    Map<String, CookieSet> map = Reflect.on(repository).field("map").get();
    assertEquals(1, map.size());
    equals(map.get("www.ehviewer.com"), Collections.singletonList(cookieEh2));
    repository.close();
    repository = new CookieRepository(app, "cookie.db");
    map = Reflect.on(repository).field("map").get();
    assertEquals(0, map.size());
    repository.close();
}
Also used : Context(android.content.Context) Cookie(okhttp3.Cookie) HttpUrl(okhttp3.HttpUrl) Test(org.junit.Test)

Example 33 with Level

use of okhttp3.logging.HttpLoggingInterceptor.Level in project Qblog_Android by qiaoyhh.

the class HttpModule method provideClient.

@Singleton
@Provides
OkHttpClient provideClient(OkHttpClient.Builder builder) {
    // if (BuildConfig.DEBUG) {
    // HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    // loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
    // builder.addInterceptor(loggingInterceptor);
    // }
    // 日志显示级别
    HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
    // 新建log拦截器
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {

        @Override
        public void log(String message) {
            Logger.e("okhttp  URL====" + message);
        }
    });
    loggingInterceptor.setLevel(level);
    File cacheFile = new File(Constants.PATH_CACHE);
    Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
    Interceptor cacheInterceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!SystemUtil.isNetworkConnected()) {
                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
            }
            Response response = chain.proceed(request);
            if (SystemUtil.isNetworkConnected()) {
                int maxAge = 0;
                // 有网络时, 不缓存, 最大保存时长为0
                response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge).removeHeader("Pragma").build();
            } else {
                // 无网络时,设置超时为4周
                int maxStale = 60 * 60 * 24 * 28;
                response.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).removeHeader("Pragma").build();
                Logger.e("无网络=======" + response.toString());
            }
            return response;
        }
    };
    // Interceptor apikey = new Interceptor() {
    // @Override
    // public Response intercept(Chain chain) throws IOException {
    // Request request = chain.request();
    // request = request.newBuilder()
    // .addHeader("apikey",Constants.KEY_API)
    // .build();
    // return chain.proceed(request);
    // }
    // }
    // 设置统一的请求头部参数
    // builder.addInterceptor(apikey);
    // builder.addInterceptor(loggingInterceptor);
    // 设置缓存
    builder.addNetworkInterceptor(cacheInterceptor);
    builder.addInterceptor(cacheInterceptor);
    builder.cache(cache);
    // 设置超时
    builder.connectTimeout(15, TimeUnit.SECONDS);
    builder.readTimeout(20, TimeUnit.SECONDS);
    builder.writeTimeout(20, TimeUnit.SECONDS);
    // 错误重连
    builder.retryOnConnectionFailure(true);
    return builder.build();
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) File(java.io.File) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Cache(okhttp3.Cache) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Example 34 with Level

use of okhttp3.logging.HttpLoggingInterceptor.Level in project runelite by runelite.

the class HiscoreService method lookupUsername.

public HiscoreResultBuilder lookupUsername(String username, HttpUrl hiscoreUrl) throws IOException {
    HttpUrl url = hiscoreUrl.newBuilder().addQueryParameter("player", username).build();
    log.debug("Built URL {}", url);
    Request okrequest = new Request.Builder().url(url).build();
    String responseStr;
    try (Response okresponse = RuneLiteAPI.CLIENT.newCall(okrequest).execute()) {
        if (!okresponse.isSuccessful()) {
            switch(HttpStatus.valueOf(okresponse.code())) {
                case NOT_FOUND:
                    throw new NotFoundException();
                default:
                    throw new InternalServerErrorException("Error retrieving data from Jagex Hiscores: " + okresponse.message());
            }
        }
        responseStr = okresponse.body().string();
    }
    CSVParser parser = CSVParser.parse(responseStr, CSVFormat.DEFAULT);
    HiscoreResultBuilder hiscoreBuilder = new HiscoreResultBuilder();
    hiscoreBuilder.setPlayer(username);
    int count = 0;
    for (CSVRecord record : parser.getRecords()) {
        if (count++ >= HiscoreSkill.values().length) {
            log.warn("Jagex Hiscore API returned unexpected data");
            // rest is other things?
            break;
        }
        // rank, level, experience
        int rank = Integer.parseInt(record.get(0));
        int level = Integer.parseInt(record.get(1));
        // items that are not skills do not have an experience parameter
        long experience = -1;
        if (record.size() == 3) {
            experience = Long.parseLong(record.get(2));
        }
        Skill skill = new Skill(rank, level, experience);
        hiscoreBuilder.setNextSkill(skill);
    }
    return hiscoreBuilder;
}
Also used : Request(okhttp3.Request) NotFoundException(net.runelite.http.service.util.exception.NotFoundException) HttpUrl(okhttp3.HttpUrl) HiscoreEndpoint(net.runelite.http.api.hiscore.HiscoreEndpoint) Response(okhttp3.Response) Skill(net.runelite.http.api.hiscore.Skill) HiscoreSkill(net.runelite.http.api.hiscore.HiscoreSkill) CSVParser(org.apache.commons.csv.CSVParser) InternalServerErrorException(net.runelite.http.service.util.exception.InternalServerErrorException) CSVRecord(org.apache.commons.csv.CSVRecord)

Example 35 with Level

use of okhttp3.logging.HttpLoggingInterceptor.Level in project edx-app-android by edx.

the class WebViewUtil method loadUrlBasedOnOsVersion.

/**
 * Simply loads a url within a WebView for Marshmallow & above and differently in case of
 * Lollipop & below.<br/>
 * WebViews prior to Marshmallow (API Level 23) don't provide a way to get the HTTP status
 * codes if the url being loaded fails.<br/>
 * This utility function solves this by making a server call using the url provided to query if
 * an error is being return and show error or move on to load the url in WebView, if the server
 * is responding correctly.
 * <p>
 * Inspiration for this solution has been taken from this link:
 * https://stackoverflow.com/questions/11889020/get-http-status-code-in-android-webview/21609608#21609608
 *
 * @param context              Current context.
 * @param webView              The WebView to load the URL into.
 * @param url                  The URL to load.
 * @param viewInterface        WebView's callbacks interface.
 * @param errorNotification    The notification setup for showing/hiding errors.
 * @param okHttpClientProvider The utility to make server calls.
 * @param actionTextResId      The resource ID of the action button text.
 * @param actionListener       The callback to be invoked when the action button is clicked.
 */
public static void loadUrlBasedOnOsVersion(@NonNull final Context context, @NonNull final WebView webView, @NonNull final String url, @NonNull final WebViewStatusListener viewInterface, @NonNull final FullScreenErrorNotification errorNotification, @NonNull OkHttpClientProvider okHttpClientProvider, @StringRes final int actionTextResId, @Nullable final View.OnClickListener actionListener) {
    if (!NetworkUtil.isConnected(context)) {
        errorNotification.showError(context, new IOException(), actionTextResId, actionListener);
    } else {
        errorNotification.hideError();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            viewInterface.showLoadingProgress();
            okHttpClientProvider.get().newCall(new Request.Builder().url(url).get().build()).enqueue(new Callback() {

                @Override
                public void onFailure(Call call, final IOException e) {
                    webView.post((new Runnable() {

                        @Override
                        public void run() {
                            errorNotification.showError(context, e, actionTextResId, actionListener);
                            viewInterface.hideLoadingProgress();
                            viewInterface.clearWebView();
                        }
                    }));
                }

                @Override
                public void onResponse(Call call, final okhttp3.Response response) throws IOException {
                    webView.post(new Runnable() {

                        @Override
                        public void run() {
                            final int responseCode = response.code();
                            if (responseCode >= HttpStatus.BAD_REQUEST) {
                                errorNotification.showError(context, new HttpStatusException(Response.error(responseCode, ResponseBody.create(MediaType.parse("text/plain"), response.message()))), actionTextResId, actionListener);
                                viewInterface.hideLoadingProgress();
                                viewInterface.clearWebView();
                            } else {
                                webView.loadUrl(url);
                            }
                        }
                    });
                }
            });
        } else {
            webView.loadUrl(url);
        }
    }
}
Also used : Call(okhttp3.Call) Callback(okhttp3.Callback) Request(okhttp3.Request) HttpStatusException(org.edx.mobile.http.HttpStatusException) IOException(java.io.IOException)

Aggregations

Request (okhttp3.Request)14 Response (okhttp3.Response)13 IOException (java.io.IOException)12 ResponseBody (okhttp3.ResponseBody)12 Test (org.junit.Test)12 HttpUrl (okhttp3.HttpUrl)9 RequestBody (okhttp3.RequestBody)8 Charset (java.nio.charset.Charset)7 Headers (okhttp3.Headers)7 OkHttpClient (okhttp3.OkHttpClient)7 MockResponse (okhttp3.mockwebserver.MockResponse)7 Buffer (okio.Buffer)7 BufferedSource (okio.BufferedSource)7 Context (android.content.Context)6 Connection (okhttp3.Connection)6 MediaType (okhttp3.MediaType)6 Protocol (okhttp3.Protocol)6 HttpHeaders (okhttp3.internal.http.HttpHeaders)6 EOFException (java.io.EOFException)5 ArrayList (java.util.ArrayList)5