当前位置: 首页 > 知识库问答 >
问题:

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

柏高丽
2023-03-14

大家好,我最近更新了我的库,升级了改版和OKHTTP。我正在使用的新版本包括以下导入/版本:

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

4)reverfit-编译“com.squareup.reverfit2:reverfit:2.1.0”

5)改造Gson转换器-编译'com.squareup.retrofit2:converter-gson:2.0.0-beta3'

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

我遇到的问题是,当我发送一个出站呼叫时,它基本上‘忽略’了路径的注释。

我的翻新客户端类:

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;
}

虽然所有这些在过去都很好地工作,但现在在更新的库中就不再起作用了。问题是它正在“忽略”路径,这样它就不会发送这个调用:

获取请求: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

共有1个答案

凌运恒
2023-03-14

您正在拦截器中重置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);
 类似资料:
  • 问题内容: 我正在使用具有“很高”的xlabel的位置绘制数据集(这是在TeX中渲染的公式,其中包含一个分数,因此其高度等于几行文本)。 无论如何,当我绘制数字时,公式的底部总是被切除。更改图形大小似乎无济于事,而且我还无法弄清楚如何将x轴“向上”移动以为xlabel腾出空间。诸如此类的东西将是一个合理的临时解决方案,但最好的办法是使matplotlib自动识别标签被切断并相应调整大小。 这是我的

  • 我尝试在Jasper报告中格式化日期,它适用于Windows但不适用于Linux。对于Linux,结果文本被截断。 JRXML: Maven依赖关系: 我读到: 用jasperreport生成的PDF在Linux上显示不佳,但在Mac上显示良好,可能与os有关吗? http://community.jaspersoft.com/questions/527138/pdf-text-truncated

  • 我已经使用VsCode从Java项目中创建了一个Jar文件,并且在我的pc中工作得很好。 我试着用一台没有Java的笔记本电脑来运行这样的Jar;所以我刚刚下载并安装了最新版本的JRE(https://www.java.com/es/download/ie_manual.jsp)因为这是运行的唯一要求。罐子 但是,当我尝试在这个Separate笔记本电脑中运行Jar时,我收到一条毫无意义的错误消息

  • 当运行一个改型应用程序时,我得到以下错误: E/AndroidRuntime:致命异常:OkHttp Dispatcher进程:fr.univ_lehavre.greah.naoderapp,PID:20894java.lang.NosuchMethoderror:lokhttp3/internal/platform类中没有虚方法日志(ljava/lang/string;)V;或其超级类('OKH

  • 问题内容: 我有一个长度为10 的类型的列: 在此列中,我插入了一个太长的数字: 当我查看表格中的内容时,数字现在是: 2147483647 变成了为什么,为什么? 为什么没有被截断? 这种转换背后的机制是什么,可以使用某些公式来计算结果数吗? 我不是在寻找解决方案。我只想了解具体数字。 问题答案: http://dev.mysql.com/doc/refman/5.0/en/integer- t