标签: okhttp3

使用Retrofit 2进行记录

我正在尝试获取请求中发送的确切JSON.这是我的代码:

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor(){
   @Override public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
      Request request = chain.request();
      Log.e(String.format("\nrequest:\n%s\nheaders:\n%s",
                          request.body().toString(), request.headers()));
      com.squareup.okhttp.Response response = chain.proceed(request);
      return response;
   }
});
Retrofit retrofit = new Retrofit.Builder()
   .baseUrl(API_URL)
   .addConverterFactory(GsonConverterFactory.create())
   .client(client).build();
Run Code Online (Sandbox Code Playgroud)

但我只在日志中看到这个:

request:
com.squareup.okhttp.RequestBody$1@3ff4074d
headers:
Content-Type: application/vnd.ll.event.list+json
Run Code Online (Sandbox Code Playgroud)

我怎么做正确的记录,考虑到拆除setLog()setLogLevel()我们使用了改造1使用哪个?

java retrofit retrofit2 okhttp3

287
推荐指数
8
解决办法
14万
查看次数

NoClassDefFoundError:解析失败:Lokhttp3/internal/Platform

我正在使用Retrofit2图书馆.

我已经尝试更新最新版本:Retrofit2,Gson,Rxjava,OKHttp,HttpLoggingInterceptor ...在build.gradle文件中

build.grade 在申请中

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'
})

// Default - Android Component
testCompile 'junit:junit:4.12'
compile 'com.android.support:design:24.2.1'
compile 'com.android.support:appcompat-v7:24.2.1'

// Retrofit2 + Gson
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.0'
compile 'com.squareup.okhttp3:okhttp:3.4.1'

// RxJva
compile 'io.reactivex:rxandroid:1.2.0'
compile 'io.reactivex:rxjava:1.1.4'
}
Run Code Online (Sandbox Code Playgroud)

但我得到了错误

 > Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lokhttp3/internal/Platform;
at okhttp3.logging.HttpLoggingInterceptor$Logger$1.log(HttpLoggingInterceptor.java:112)
at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:160)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at internal.NetworkModule$1.intercept(NetworkModule.java:150)
Run Code Online (Sandbox Code Playgroud)

在下面的代码中

Interceptor provideInterceptor(final …
Run Code Online (Sandbox Code Playgroud)

java android retrofit2 okhttp3

44
推荐指数
1
解决办法
2万
查看次数

使用OkHttp 3自动处理cookie

我正在使用okhttp 3.0.1.

每个我在哪里获得与okhttp2一起进行cookie处理的例子

OkHttpClient client = new OkHttpClient();
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
client.setCookieHandler(cookieManager);
Run Code Online (Sandbox Code Playgroud)

可以请一些人指导我如何在版本3中使用.在版本3中不存在setCookieHandler方法.

cookies okhttp3

33
推荐指数
6
解决办法
5万
查看次数

java.net.SocketTimeoutException:timeout

随着OkHttp图书馆,应用程序面临以下SocketTimeoutException问题.如果请求大小较小,那么它工作正常(小于1MB).我在10秒内收到此异常,即使我的socket timeout(readTimeout)值更高.它总是失败的请求(大小是1.8MB).当我执行请求时HttpUrlConnection它工作正常.什么可能是失败的原因?

   03-29 12:16:38.997 32066-4018/com.mobile W/System.err: java.net.SocketTimeoutException: timeout
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okio.Okio$3.newTimeoutException(Okio.java:207)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okio.AsyncTimeout.exit(AsyncTimeout.java:261)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okio.AsyncTimeout$1.write(AsyncTimeout.java:158)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okio.RealBufferedSink.emitCompleteSegments(RealBufferedSink.java:176)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okio.RealBufferedSink.write(RealBufferedSink.java:46)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okhttp3.internal.http.Http1xStream$FixedLengthSink.write(Http1xStream.java:286)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okio.RealBufferedSink.emitCompleteSegments(RealBufferedSink.java:176)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okio.RealBufferedSink.write(RealBufferedSink.java:96)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okhttp3.RequestBody$2.writeTo(RequestBody.java:96)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okhttp3.internal.http.HttpEngine$NetworkInterceptorChain.proceed(HttpEngine.java:704)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err: …
Run Code Online (Sandbox Code Playgroud)

java android httpurlconnection okhttp3

33
推荐指数
5
解决办法
5万
查看次数

升级到OkHttp3后,OkHttpClient抛出异常

我正在使用以下代码行为使用Retrofit2发送的所有请求添加默认标头:

private static OkHttpClient defaultHttpClient = new OkHttpClient();
static {
    defaultHttpClient.networkInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request().newBuilder()
                    .addHeader("Accept", "Application/JSON").build();
            return chain.proceed(request);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

在将改造升级到beta-3版本之后,我还必须将OkHttp升级到OkHttp3(实际上我只是将包名称从okhttp更改为okhttp3,该库包含在改造中).之后我从这一行得到例外:

defaultHttpClient.networkInterceptors().add(new Interceptor());
Run Code Online (Sandbox Code Playgroud)

引起:java.util.Collections的java.lang.UnsupportedOperationException $ UnmodifiableCollection.add(Collections.java:932)


引起:java.lang.ExceptionInInitializerError


这里有什么问题?

android retrofit okhttp retrofit2 okhttp3

31
推荐指数
1
解决办法
1万
查看次数

OkHttp:避免泄露连接警告

我正在使用OkHttp 3,我一直在泄漏连接警告:

WARNING: A connection to https://help.helpling.com/ was leaked. Did you forget to close a response body?
Jul 14, 2016 6:57:09 PM okhttp3.ConnectionPool pruneAndGetAllocationCount
Run Code Online (Sandbox Code Playgroud)

每次我得到一个ResponseBody,我要么调用.string()哪个可以为我关闭流,或者我在一个finally块中明确地关闭它,方法如下:

ResponseBody responseBody = response.body();
try (Reader responseReader = responseBody.charStream()) {
    ...
}
finally {
    responseBody.close();
}
Run Code Online (Sandbox Code Playgroud)

我的应用程序大量使用网络,但这种警告经常出现.我从来没有看到造成这种推测泄漏的任何问题,但我还是想知道,如果什么我做错了.

谁能对此有所了解?

java memory-leaks okhttp3

28
推荐指数
2
解决办法
2万
查看次数

Android Retrofit2刷新Oauth 2令牌

我正在使用RetrofitOkHttp库.所以Authenticator如果获得401响应,我有哪个authanticate用户.

build.gradle是这样的:

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.okhttp3:okhttp:3.1.2'
Run Code Online (Sandbox Code Playgroud)

我的习惯Authenticator在这里:

import java.io.IOException;
import okhttp3.Authenticator;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;

public class CustomAuthanticator  implements Authenticator {
@Override
public Request authenticate(Route route, Response response) throws IOException {

    //refresh access token via refreshtoken

    Retrofit client = new Retrofit.Builder()
            .baseUrl(baseurl)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    APIService service = client.create(APIService.class);
    Call<RefreshTokenResult> refreshTokenResult=service.refreshUserToken("application/json", "application/json", "refresh_token",client_id,client_secret,refresh_token);
    //this is syncronous retrofit request
    RefreshTokenResult refreshResult= refreshTokenResult.execute().body();
    //check if response equals 400 , …
Run Code Online (Sandbox Code Playgroud)

android oauth-2.0 okhttp retrofit2 okhttp3

26
推荐指数
1
解决办法
2万
查看次数

Retrofit API调用收到"HTTP FAILED:java.io.IOException:Cancelled"

无法弄清楚为什么会这样.我的调用不会触发任何一个rx回调(onCompleted(),onError(),onNext()).我收到的唯一的东西是这个okhttp输出:

D/OkHttp: --> GET https://api.privatbank.ua/p24api/exchange_rates?json=true&date=20.11.2016 http/1.1
D/OkHttp: --> END GET
D/OkHttp: <-- HTTP FAILED: java.io.IOException: Canceled
Run Code Online (Sandbox Code Playgroud)

改造模块:

@Module
public class RestModule {

    @Provides
    @Singleton
    public HttpLoggingInterceptor providesHttpLogginInterceptor() {
        return new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);
    }

    @Provides
    @Singleton
    public OkHttpClient providesOkHttpClient(@NonNull HttpLoggingInterceptor loggingInterceptor) {
        return new OkHttpClient.Builder()
            .addInterceptor(loggingInterceptor)
            .connectTimeout(ConstantsManager.CONNECTION_TIME_OUT, TimeUnit.SECONDS)
            .readTimeout(ConstantsManager.READ_TIME_OUT, TimeUnit.SECONDS)
            .build();
    }

    @Provides
    @Singleton
    public Gson providesGson() {
        return new GsonBuilder().create();
    }

    @Provides
    @Singleton
    public Retrofit providesRetrofit(@NonNull OkHttpClient okHttpClient, @NonNull Gson gson) {
        return new Retrofit.Builder()
            .baseUrl(ConstantsManager.BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(SimpleXmlConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build(); …
Run Code Online (Sandbox Code Playgroud)

android rx-java rx-android retrofit2 okhttp3

24
推荐指数
1
解决办法
1万
查看次数

Android Retrofit 2,addInterceptor和addNetworkInterceptor之间的差异用于编辑响应

我一直在尝试实现拦截器(OkHttp 3.2和Retrofit 2),以便在作为响应返回之前编辑JSON响应.我们请求数据的服务器返回成功或错误的不同数据依赖性,这使得难以映射对象.

我试图通过将拦截器添加到Retrofit作为NetworkInterceptor来实现,但返回的字符串没有格式.

@Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        Response response = chain.proceed(request);
        try {

            final String responseString = new String(response.body().bytes() ); 

            LOGD("OkHttp-NET-Interceptor", "Response: " + responseString);

            String  newResponseString = editResponse( responseString );

            LOGD("OkHttp-NET-Interceptor", "Response edited: " + newResponseString);
            return  response.newBuilder()
                    .body(ResponseBody.create(response.body().contentType(), newResponseString))
                    .build();

        }catch (Exception ex){
            return response;
        }
    }
Run Code Online (Sandbox Code Playgroud)

responseString有一个没有任何可理解格式的字符串.

在更改为普通拦截器之后,字符串具有能够转换为JSONObject的格式.

可以告诉我某些回复之间的差异吗?

为什么这行新的String(response.body().bytes()); 返回不同的内容?

android interceptor retrofit2 okhttp3

23
推荐指数
1
解决办法
9801
查看次数

如何在Android中的OKHTTP 3.x中动态(或循环)发送post参数?

我正在使用OKHTTP 3.x版本.我想发布多个参数,并希望在循环中添加参数.我知道在2.x版本中,我可以使用FormEncodingBuilder并在循环中添加params,然后从中创建一个请求体.但在3.x中,该类已被删除.

这是我目前的代码:

RequestBody formBody = new FormBody.Builder()
            .add("Param1", value1)
            .add("Param2", value2)
            .build();
Request request = new Request.Builder()
            .url("url")
            .post(formBody)
            .build();
Run Code Online (Sandbox Code Playgroud)

现在我想添加5个参数但是在一个循环中,即通过在循环中构建formbody来创建请求体.就像我上面写的那样,我知道如何在OKHTTP版本2.x中执行它,但我使用的是版本3.x.

任何帮助或指导表示赞赏.

提前致谢

android okhttp3

20
推荐指数
2
解决办法
3万
查看次数