gpt4 book ai didi

android - 如何使用 retrofit2 (v2.0.0-beta3) 处理响应

转载 作者:行者123 更新时间:2023-11-30 01:39:39 25 4
gpt4 key购买 nike

我正在使用最新版本的改造,retrofit2,v2.0.0-beta3。 API 响应是用户对象或空响应(空值)。如果我发送正确的用户名/密码,然后 handle 进入带有成功用户对象的 onResponse 方法。但是如果发送错误的密码,那么 API 将不会返回任何内容,响应 header 中的值很少。但是我在 onFailure(Throwable) 中得到了 MalformedJsonException

“com.google.gson.stream.MalformedJsonException:使用 JsonReader.setLenient(true) 在第 1 行第 1 列路径 $ 处接受格式错误的 JSON”

这是错误的截图, enter image description here

我认为应该有某种方式来处理空响应和读取响应 header ,使用 ResponseInceptor 或 Custom CallBack。但不知道如何使用它。

这是代码,

// Define the interceptor, add authentication headers
Interceptor interceptor = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder().addHeader("Authorization", new ITAuthorizationUtil().getAuthorization(user.getMobile_no(), user.getPassword())).build();
return chain.proceed(newRequest);
}
};

// Add the interceptor to OkHttpClient
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseURL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();

ITAPIEndpointsInterface apiEndpointsInterface = retrofit.create(ITAPIEndpointsInterface.class);


///
Call<User> call = apiEndpointsInterface.userLogin(senderId, applicationId, registrationId);

//asynchronous call
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Response<User> response) {
ApiResponse apiResponse = ITAPIStatusInfo.getApiErrorObject_Retrofit(response.headers());
onSuccess( response.body(),apiResponse);
}

@Override
public void onFailure(Throwable t) {
Log.d(">>> ",t.getMessage());
}

});

最佳答案

你需要提供一个GSON实例给Retrofit。

尝试:

Gson gson = new GsonBuilder().create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseURL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client)
.build();

关于android - 如何使用 retrofit2 (v2.0.0-beta3) 处理响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34671542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com