Search in sources :

Example 86 with Header

use of okhttp3.internal.http2.Header in project AntennaPod by AntennaPod.

the class NetworkUtils method getFeedMediaSizeObservable.

public static Observable<Long> getFeedMediaSizeObservable(FeedMedia media) {
    return Observable.create(new Observable.OnSubscribe<Long>() {

        @Override
        public void call(Subscriber<? super Long> subscriber) {
            if (!NetworkUtils.isDownloadAllowed()) {
                subscriber.onNext(0L);
                subscriber.onCompleted();
                return;
            }
            long size = Integer.MIN_VALUE;
            if (media.isDownloaded()) {
                File mediaFile = new File(media.getLocalMediaUrl());
                if (mediaFile.exists()) {
                    size = mediaFile.length();
                }
            } else if (!media.checkedOnSizeButUnknown()) {
                // only query the network if we haven't already checked
                String url = media.getDownload_url();
                if (TextUtils.isEmpty(url)) {
                    subscriber.onNext(0L);
                    subscriber.onCompleted();
                    return;
                }
                OkHttpClient client = AntennapodHttpClient.getHttpClient();
                Request.Builder httpReq = new Request.Builder().url(url).header("Accept-Encoding", "identity").head();
                try {
                    Response response = client.newCall(httpReq.build()).execute();
                    if (response.isSuccessful()) {
                        String contentLength = response.header("Content-Length");
                        try {
                            size = Integer.parseInt(contentLength);
                        } catch (NumberFormatException e) {
                            Log.e(TAG, Log.getStackTraceString(e));
                        }
                    }
                } catch (IOException e) {
                    subscriber.onNext(0L);
                    subscriber.onCompleted();
                    Log.e(TAG, Log.getStackTraceString(e));
                    // better luck next time
                    return;
                }
            }
            Log.d(TAG, "new size: " + size);
            if (size <= 0) {
                // they didn't tell us the size, but we don't want to keep querying on it
                media.setCheckedOnSizeButUnknown();
            } else {
                media.setSize(size);
            }
            subscriber.onNext(size);
            subscriber.onCompleted();
            DBWriter.setFeedMedia(media);
        }
    }).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread());
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Observable(rx.Observable) Response(okhttp3.Response) File(java.io.File)

Example 87 with Header

use of okhttp3.internal.http2.Header in project AntennaPod by AntennaPod.

the class AntennapodHttpClient method newBuilder.

/**
     * Creates a new HTTP client.  Most users should just use
     * getHttpClient() to get the standard AntennaPod client,
     * but sometimes it's necessary for others to have their own
     * copy so that the clients don't share state.
     * @return http client
     */
@NonNull
public static OkHttpClient.Builder newBuilder() {
    Log.d(TAG, "Creating new instance of HTTP client");
    System.setProperty("http.maxConnections", String.valueOf(MAX_CONNECTIONS));
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    // detect 301 Moved permanently and 308 Permanent Redirect
    builder.networkInterceptors().add(chain -> {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if (response.code() == HttpURLConnection.HTTP_MOVED_PERM || response.code() == StatusLine.HTTP_PERM_REDIRECT) {
            String location = response.header("Location");
            if (location.startsWith("/")) {
                HttpUrl url = request.url();
                location = url.scheme() + "://" + url.host() + location;
            } else if (!location.toLowerCase().startsWith("http://") && !location.toLowerCase().startsWith("https://")) {
                HttpUrl url = request.url();
                String path = url.encodedPath();
                String newPath = path.substring(0, path.lastIndexOf("/") + 1) + location;
                location = url.scheme() + "://" + url.host() + newPath;
            }
            try {
                DBWriter.updateFeedDownloadURL(request.url().toString(), location).get();
            } catch (Exception e) {
                Log.e(TAG, Log.getStackTraceString(e));
            }
        }
        return response;
    });
    // set cookie handler
    CookieManager cm = new CookieManager();
    cm.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
    builder.cookieJar(new JavaNetCookieJar(cm));
    // set timeouts
    builder.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
    builder.readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
    builder.writeTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
    // configure redirects
    builder.followRedirects(true);
    builder.followSslRedirects(true);
    ProxyConfig config = UserPreferences.getProxyConfig();
    if (config.type != Proxy.Type.DIRECT) {
        int port = config.port > 0 ? config.port : ProxyConfig.DEFAULT_PORT;
        SocketAddress address = InetSocketAddress.createUnresolved(config.host, port);
        Proxy proxy = new Proxy(config.type, address);
        builder.proxy(proxy);
        if (!TextUtils.isEmpty(config.username)) {
            String credentials = Credentials.basic(config.username, config.password);
            builder.interceptors().add(chain -> {
                Request request = chain.request().newBuilder().header("Proxy-Authorization", credentials).build();
                return chain.proceed(request);
            });
        }
    }
    if (16 <= Build.VERSION.SDK_INT && Build.VERSION.SDK_INT < 21) {
        builder.sslSocketFactory(new CustomSslSocketFactory(), trustManager());
    }
    return builder;
}
Also used : JavaNetCookieJar(okhttp3.JavaNetCookieJar) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) HttpUrl(okhttp3.HttpUrl) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) Response(okhttp3.Response) Proxy(java.net.Proxy) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) CookieManager(java.net.CookieManager) NonNull(android.support.annotation.NonNull)

Example 88 with Header

use of okhttp3.internal.http2.Header in project OkHttp3 by MrZhousf.

the class DownUpLoadHelper method downloadFile.

/**
     * 文件下载
     */
void downloadFile(final OkHttpHelper helper) {
    try {
        final HttpInfo info = httpInfo;
        final DownloadFileInfo fileInfo = helper.getDownloadFileInfo();
        String url = fileInfo.getUrl();
        if (TextUtils.isEmpty(url)) {
            showLog("下载文件失败:文件下载地址不能为空!");
            return;
        }
        info.setUrl(url);
        ProgressCallback progressCallback = fileInfo.getProgressCallback();
        //获取文件断点
        long completedSize = fetchCompletedSize(fileInfo);
        fileInfo.setCompletedSize(completedSize);
        //添加下载任务
        if (null == downloadTaskMap)
            downloadTaskMap = new ConcurrentHashMap<>();
        if (downloadTaskMap.containsKey(fileInfo.getSaveFileNameEncrypt())) {
            showLog(fileInfo.getSaveFileName() + " 已在下载任务中");
            return;
        }
        downloadTaskMap.put(fileInfo.getSaveFileNameEncrypt(), fileInfo.getSaveFileNameEncrypt());
        Interceptor interceptor = new Interceptor() {

            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder().body(new ProgressResponseBody(originalResponse.body(), fileInfo, timeStamp, requestTag)).build();
            }
        };
        //采用新的OkHttpClient处理多线程干扰回调进度问题
        OkHttpClient httpClient = helper.getClientBuilder().addInterceptor(interceptor).build();
        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url(url).header("RANGE", "bytes=" + completedSize + "-");
        helper.getHttpHelper().addHeadsToRequest(info, requestBuilder);
        Request request = requestBuilder.build();
        helper.setRequest(request);
        helper.setHttpClient(httpClient);
        helper.getHttpHelper().responseCallback(helper.doRequestSync(), progressCallback, OkMainHandler.RESPONSE_DOWNLOAD_CALLBACK, requestTag);
        //删除下载任务
        if (null != downloadTaskMap) {
            downloadTaskMap.remove(fileInfo.getSaveFileNameEncrypt());
        }
    } catch (Exception e) {
        showLog("下载文件失败:" + e.getMessage());
    }
}
Also used : DownloadFileInfo(com.okhttplib.bean.DownloadFileInfo) OkHttpClient(okhttp3.OkHttpClient) ProgressCallback(com.okhttplib.callback.ProgressCallback) Request(okhttp3.Request) ProgressResponseBody(com.okhttplib.progress.ProgressResponseBody) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) HttpInfo(com.okhttplib.HttpInfo) Response(okhttp3.Response) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Interceptor(okhttp3.Interceptor)

Example 89 with Header

use of okhttp3.internal.http2.Header in project WordPress-Android by wordpress-mobile.

the class GravatarApi method createClient.

private static OkHttpClient createClient(final String accessToken) {
    OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
    //// uncomment the following line to add logcat logging
    //httpClientBuilder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
    // add oAuth token usage
    httpClientBuilder.addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request original = chain.request();
            Request.Builder requestBuilder = original.newBuilder().header("Authorization", "Bearer " + accessToken).method(original.method(), original.body());
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });
    return httpClientBuilder.build();
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Interceptor(okhttp3.Interceptor)

Example 90 with Header

use of okhttp3.internal.http2.Header in project spring-framework by spring-projects.

the class WebClientIntegrationTests method plainText.

@Test
public void plainText() throws Exception {
    this.server.enqueue(new MockResponse().setBody("Hello Spring!"));
    Mono<String> result = this.webClient.get().uri("/greeting?name=Spring").header("X-Test-Header", "testvalue").exchange().then(response -> response.bodyToMono(String.class));
    StepVerifier.create(result).expectNext("Hello Spring!").expectComplete().verify(Duration.ofSeconds(3));
    RecordedRequest recordedRequest = server.takeRequest();
    Assert.assertEquals(1, server.getRequestCount());
    Assert.assertEquals("testvalue", recordedRequest.getHeader("X-Test-Header"));
    Assert.assertEquals("*/*", recordedRequest.getHeader(HttpHeaders.ACCEPT));
    Assert.assertEquals("/greeting?name=Spring", recordedRequest.getPath());
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)89 MockResponse (okhttp3.mockwebserver.MockResponse)82 Request (okhttp3.Request)75 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)56 Response (okhttp3.Response)54 IOException (java.io.IOException)53 RequestBody (okhttp3.RequestBody)24 OkHttpClient (okhttp3.OkHttpClient)22 Call (okhttp3.Call)20 Callback (okhttp3.Callback)19 Interceptor (okhttp3.Interceptor)14 ResponseBody (okhttp3.ResponseBody)12 FormBody (okhttp3.FormBody)11 Headers (okhttp3.Headers)11 ArrayList (java.util.ArrayList)10 Map (java.util.Map)10 List (java.util.List)9 JSONObject (org.json.JSONObject)8 File (java.io.File)6 HashMap (java.util.HashMap)6