OkHttp2.0不再支持此OkHttpStack:https://gist.github.com/JakeWharton/5616899
将OkHttp 2.0.0与Volley集成的当前模式是什么?
请考虑以下代码:
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("text/plain; charset=utf-8"); // [A]
RequestBody body = RequestBody.create(mediaType, media);
String[] aclHeader = "x-goog-acl:public-read".split(":");
Request request = new Request.Builder()
.addHeader("Content-Type", "text/plain") // [B]
.addHeader(aclHeader[0], aclHeader[1])
.url(url)
.put(body)
.build();
Response response = client.newCall(request).execute();
Run Code Online (Sandbox Code Playgroud)
我从客户端访问GCS,并使用以前签名的URL.
问题:似乎okhttp将为身体[A]声明的字符集添加到URL中(至少对于text/plain),即使它未在[B]中声明.这会弄乱我签名的URL,GCS会返回403 Forbidden.
但这不是应该的.至少在使用签名URL时,必须将这些URL完全按照声明的方式发送到服务器.
我尝试使用Apache http客户端(我不想在生产中使用,因为okhttpclient已经是我的安装的一部分)并且该客户端不会暴露这种行为:
String[] aclHeader = "x-goog-acl:public-read".split(":");
StatusLine statusLine = Request
.Put(url)
.addHeader("Content-Type", "text/plain")
.addHeader(aclHeader[0], aclHeader[1])
.bodyByteArray(media)
.execute().returnResponse().getStatusLine();
Run Code Online (Sandbox Code Playgroud)
有没有办法抑制okhttp中的行为,它是添加到Content-Type还是冗余地传输了Body-Type中的Content-Type?
是否有关于如何向Retrofit + OkHttp 添加缓存和ETAG/ If-None-Match支持的正确解释?我正在努力为Etag2个项目添加支持,起初我怀疑HTTP标头可能存在问题,另一个项目已正确设置,缓存仍无法按预期工作.
以下是我试图让它发挥作用.结果显示缓存似乎在应用程序的同一个实例中工作,但是一旦我重新启动 - 所有内容都会再次加载.此外,在我的日志中,我没有看到If-None-Match被添加到请求中,因此我假设服务器不知道ETag并且仍然完全重新计算响应.
以下是一些代码示例:
public class RetrofitHttpClient extends UrlConnectionClient
{
private OkUrlFactory generateDefaultOkUrlFactory()
{
OkHttpClient client = new com.squareup.okhttp.OkHttpClient();
try
{
Cache responseCache = new Cache(baseContext.getCacheDir(), SIZE_OF_CACHE);
client.setCache(responseCache);
}
catch (Exception e)
{
Logger.log(this, e, "Unable to set http cache");
}
client.setConnectTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
client.setReadTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS);
return new OkUrlFactory(client);
}
private final OkUrlFactory factory;
public RetrofitHttpClient()
{
factory = generateDefaultOkUrlFactory();
}
@Override
protected HttpURLConnection openConnection(retrofit.client.Request request) throws …Run Code Online (Sandbox Code Playgroud) 在我们的应用程序中,我使用此代码下载图像文件.我需要在UI上显示下载进度(以百分比形式下载的字节数).我如何在此代码中获得下载进度?我搜索了解决方案,但仍无法自行完成.
Observable<String> downloadObservable = Observable.create(
sub -> {
Request request = new Request.Builder()
.url(media.getMediaUrl())
.build();
Response response = null;
try {
response = http_client.newCall(request).execute();
if (response.isSuccessful()) {
Log.d(TAG, "response.isSuccessful()");
String mimeType = MimeTypeMap.getFileExtensionFromUrl(media.getMediaUrl());
File file = new File(helper.getTmpFolder() + "/" + helper.generateUniqueName() + "test." + mimeType);
BufferedSink sink = Okio.buffer(Okio.sink(file));
sink.writeAll(response.body().source());
sink.close();
sub.onNext(response.toString());
sub.onCompleted();
} else {
sub.onError(new IOException());
}
} catch (IOException e) {
e.printStackTrace();
}
}
);
Subscriber<String> mySubscriber = new Subscriber<String>() {
@Override
public void …Run Code Online (Sandbox Code Playgroud) 在Android应用上使用com.squareup.okhttp:okhttp:2.4.0with com.squareup.retrofit:retrofit:1.9.0,尝试通过HTTPS与服务器REST API进行通信,该API使用自签名证书.
服务器密钥库有一个私钥和2个证书,服务器和根证书.openssl s_client输出 -
Certificate chain
0 s:/C=...OU=Dev/CN=example.com
i:/C=... My CA/emailAddress=info@example.com
1 s:/C=... My CA/emailAddress=info@example.com
i:/C=... My CA/emailAddress=info@example.com
Run Code Online (Sandbox Code Playgroud)
在Android应用程序中,OkHttp使用根证书的SHA1签名进行初始化 -
CertificatePinner certificatePinner = new CertificatePinner.Builder()
.add("example.com", "sha1/5d...3b=")
.build();
OkHttpClient client = new OkHttpClient();
client.setCertificatePinner(certificatePinner);
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://example.com")
.setClient(new OkClient(client))
.build();
Run Code Online (Sandbox Code Playgroud)
但是当尝试发送请求失败时会出现异常 -
retrofit.RetrofitError: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:395)
at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:240)
at java.lang.reflect.Proxy.invoke(Proxy.java:397)
at $Proxy1.report(Unknown Source)
...
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at …Run Code Online (Sandbox Code Playgroud) 我想在拦截器上保存SharedPreferences上的一些东西.我找不到办法,因为我找不到一种方法来访问Interceptor上的上下文(所以不可能使用PreferencesManager等).
public class CookieInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
PreferenceManager.getDefaultSharedPreferences(Context ??)
}}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗 ?
我正在使用AndroidStudio和OkHttp的最新版本.
谢谢 ;)
我已经使用了okhttp,它可以正常使用以下依赖:
compile 'com.squareup.okhttp:okhttp:2.3.0'
Run Code Online (Sandbox Code Playgroud)
最近我更新了:
compile 'com.squareup.okhttp3:okhttp:3.0.0-RC1'
Run Code Online (Sandbox Code Playgroud)
它显示MultipartBuilder无法解决的错误.
我正在使用我的上传文件上传答案上传图片.
有没有办法实现相同的使用okhttp:3.0.0-RC1?
我尝试使用OkHttp和Picasso(按照这个答案)对我从Firebase存储下载的图像进行磁盘缓存.现在,该应用程序提供例外和崩溃.我看过这些帖子:帖子1,帖子2但我没有找到任何相关的解决方案.我也试图清理和重建项目,但没有运气.
这是build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "social.com.networking.social.media.app"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
multiDexEnabled true
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.support:design:25.1.0'
compile 'br.com.mauker.materialsearchview:materialsearchview:1.2.0'
compile 'com.alirezaafkar:toolbar:1.1.1'
compile 'com.github.mancj:MaterialSearchBar:0.3.5'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.daimajia.slider:library:1.1.5@aar'
compile …Run Code Online (Sandbox Code Playgroud) 使用Http发送Base64编码的字符串作为标头时,我收到错误响应
Unexpected char 0x0a at 28 in header value: I99Uy+HjG5PpEhmi8vZgm0W7KDQ=
用法:
String encodedHeader = Base64.encodeToString(value.getBytes(), Base64.DEFAULT);
header.put("auth", encodedHeader);
我在Android应用程序中使用Retrofit,这反过来意味着我使用OkHttp.我刚刚去了Alpha,并在我的崩溃报告中看到了许多非致命的异常被记录.所有这些都源于我的okhttp拦截器,然后记录的异常似乎都是在网络可能不稳定或连接丢失等情况下有效的事情.
我怎样才能做到这一点,以便这些例外不会记录到崩溃关系中,从而混淆了我对应用程序中出现的异常的看法?
一些例外的例子:
> Non-fatal Exception: javax.net.ssl.SSLHandshakeException
Connection closed by peer
okhttp3.internal.connection.RealConnection.connectTls (RealConnection.java:281)
okhttp3.internal.connection.RealConnection.establishProtocol (RealConnection.java:251)
okhttp3.internal.connection.RealConnection.connect (RealConnection.java:151)
okhttp3.internal.connection.StreamAllocation.findConnection (StreamAllocation.java:192)
okhttp3.internal.connection.StreamAllocation.findHealthyConnection (StreamAllocation.java:121)
okhttp3.internal.connection.StreamAllocation.newStream (StreamAllocation.java:100)
okhttp3.internal.connection.ConnectInterceptor.intercept (ConnectInterceptor.java:42)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67)
okhttp3.internal.cache.CacheInterceptor.intercept (CacheInterceptor.java:93)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67)
okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.java:93)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.java:120)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67)
MY_INTERCEPTOR.intercept (AuthenticationInterceptor.java:30)
Run Code Online (Sandbox Code Playgroud)
和
> Non-fatal Exception: javax.net.ssl.SSLException
Read error: ssl=0xdee45cc0: I/O error during system call, Software caused connection abort
okio.Okio$2.read (Okio.java:139)
okio.AsyncTimeout$2.read (AsyncTimeout.java:237)
okio.RealBufferedSource.indexOf (RealBufferedSource.java:345)
okio.RealBufferedSource.readUtf8LineStrict (RealBufferedSource.java:217)
okio.RealBufferedSource.readUtf8LineStrict (RealBufferedSource.java:211)
okhttp3.internal.http1.Http1Codec.readResponseHeaders (Http1Codec.java:189)
okhttp3.internal.http.CallServerInterceptor.intercept (CallServerInterceptor.java:75)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92) …Run Code Online (Sandbox Code Playgroud)