为什么我的 Web 请求在使用最新版本的 Retrofit / OkHttp 时被截断

Why does my Web request get Truncated when using the newest versions of Retrofit / OkHttp

大家好,我最近更新了我的库并升级了 Retrofit 和 OkHttp。我使用的新版本包括这些导入/版本:

1) Gson - 编译'com.google.code.gson:gson:2.7'

2) OkHttp - 编译'com.squareup.okhttp3:okhttp:3.4.1'

3) OkHttp 日志记录 - 编译 'com.squareup.okhttp3:logging-interceptor:3.4.1'

4)改造-编译'com.squareup.retrofit2:retrofit:2.1.0'

5) Retrofit Gson Converter - 编译 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'

我不得不更改一些实际调用的结构,但除此之外,我的代码与这些库的早期版本 (Retrofit / OkHttp 1) 基本相同。

我遇到的问题是,当我发送出站呼叫时,它本质上是 'ignoring' 路径的注释。

我的改造客户端Class:

import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;

public class RetrofitClient {

    private static RetrofitService serviceClient;

    private static final String BASE_URL = "api.myapiurl.com";
    private static HttpLoggingInterceptor.Level httpLogLevel = HttpLoggingInterceptor.Level.BODY;

    static {
        buildAClient();
    }

    public static RetrofitService getServiceClient(){
        return serviceClient;
    }

    private static void buildAClient(){

        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request.Builder builder = new Request.Builder();
                Request original = chain.request();
                builder.url(BASE_URL);
                builder.addHeader("Content-Type", "application/json");
                builder.method(original.method(), original.body());
                Request newRequest = builder.build();
                return chain.proceed(newRequest);
            }
        };
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(httpLogLevel);

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.readTimeout(60, TimeUnit.SECONDS);
        builder.writeTimeout(60, TimeUnit.SECONDS);
        builder.addInterceptor(interceptor);
        builder.addInterceptor(logging);
        builder = configureClient(builder);

        OkHttpClient client = builder.build();

        Retrofit.Builder myBuilder = new Retrofit.Builder();
        myBuilder.baseUrl(BASE_URL);
        Gson gson = new GsonBuilder()
                .setLenient()
                .setPrettyPrinting() 
                .create();
        GsonConverterFactory factory = GsonConverterFactory.create(gson);
        myBuilder.addConverterFactory(factory);
        myBuilder.client(client);
        Retrofit retrofit = myBuilder.build();
        serviceClient = retrofit.create(RetrofitService.class);

    }


    /**
     * {@link okhttp3.OkHttpClient.Builder} <-- sslSocketFactory
      */
    private static OkHttpClient.Builder configureClient(final OkHttpClient.Builder builder) {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                    TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:"
                        + Arrays.toString(trustManagers));
            }
            X509TrustManager trustManager = (X509TrustManager) trustManagers[0];

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{trustManager}, null);
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            builder.sslSocketFactory(sslSocketFactory, trustManager);
        return builder;
    }
}

我的改造服务界面:

public interface RetrofitService {
    //Version Strings
    public static final String VERSION2 = "/v2";

    //Returns a list of Order Objects
    @GET(VERSION2 + "/orders/{orderId}/getOrder")
    Call<Order> getOrder(@Path("orderId") String orderId,
                         @Query("key") String apiKey
    //I'm aware this is bad practice ^^, already spoke with server dev
    );

}

我实际拨打的电话是这样的:

    public static Order getSingleOrder(String orderId, String apiKey) {

        Call<Order> call = myService.getOrder(orderId, apiKey);

        Order toReturn = null;

        try {
            Response response = call.execute();
            toReturn = (Order) response.body();
        } catch (IOException ioe){
            ioe.printStackTrace();
        }
        return toReturn;
}

虽然所有这些在过去工作得很好,但现在它不再适用于更新的库。问题是它是 "ignoring" 路径,所以不是发送这个调用:

获取请求:http://api.myapiurl.com/orders/12345/getOrder?key=54321

现在正在提出这个请求:

获取请求:http://api.myapiurl.com/

就是这样。 api 基本字符串中 .com 之后的任何内容都不会发送。我正在阅读我的 logcat 和后续的 OkHttp 日志记录语句,以查看调用失败的位置:

样本:

--> GET http://api.myapiurl.com/ http/1.1
--> END GET

有谁知道为什么在我更新之前它工作正常时会发生这种情况?

感谢大家的帮助!

您正在重置拦截器中的 url --

            Request.Builder builder = new Request.Builder();
            Request original = chain.request();
            builder.url(BASE_URL);  <--!!! resets the request url to the base URL
            builder.addHeader("Content-Type", "application/json");
            builder.method(original.method(), original.body());
            Request newRequest = builder.build();
            return chain.proceed(newRequest);

尝试从现有请求中获取构建器 --

            Request original = chain.request();
            Request.Builder builder = original.newBuilder();
            builder.addHeader("Content-Type", "application/json");
            Request newRequest = builder.build();
            return chain.proceed(newRequest);