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());
}
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;
}
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());
}
}
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();
}
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());
}
Aggregations