gpt4 book ai didi

android - 使用 Retrofit 时出现 SocketTimeOut 异常

转载 作者:行者123 更新时间:2023-11-30 00:59:34 24 4
gpt4 key购买 nike

我只是尝试使用 Retrofit 进行 post api 调用。服务器正在响应正确的数据。我与 Postman (Chrome) 进行了核对。我的代码如下

公共(public)类 MainActivity 扩展 Activity 实现 retrofit2.Callback>{

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(6, TimeUnit.MINUTES)
.readTimeout(6, TimeUnit.MINUTES)
.writeTimeout(6, TimeUnit.MINUTES)
.build();


Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://kokanplaces.com/")
.addConverterFactory(GsonConverterFactory.create(gson)).client(okHttpClient)
.build();

// prepare call in Retrofit 2.0

ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);

Call<List<CityModel>> call = apiService.getCitiesList();;
//asynchronous call
call.enqueue(this);
}


@Override
public void onResponse(Call<List<CityModel>> call, Response<List<CityModel>> response) {
int code = response.code();
if (code == 200) {
for (CityModel cityModel : response.body()) {
System.out.println(
cityModel.getCityname() + " (" + cityModel.getCityId() + ")");
}


} else {
Toast.makeText(this, "Did not work: " + String.valueOf(code), Toast.LENGTH_LONG).show();
}

}

@Override
public void onFailure(Call<List<CityModel>> call, Throwable t) {
Toast.makeText(this, "failure", Toast.LENGTH_LONG).show();
System.out.println(t.fillInStackTrace());
t.printStackTrace();

}

public interface ApiInterface {
@POST("wp-json/getCities")
Call<List<CityModel>> getCitiesList();

每次它都抛出套接字超时异常。

任何解决方案都会有很大帮助。

最佳答案

我以前遇到过像你这样的问题。我通过添加自定义 OkHttpClient 来修复:

Constants.TIMEOUT_CONNECTION = 60;
private OkHttpClient getOkHttpClient() {
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(0, TimeUnit.NANOSECONDS)
.connectTimeout(Constants.TIMEOUT_CONNECTION, TimeUnit.SECONDS)
.writeTimeout(Constants.TIMEOUT_CONNECTION, TimeUnit.SECONDS)
// .sslSocketFactory(getSSLSocketFactory())
.build();
return okHttpClient;
}

和retrofitAdapter:

retrofitAdapter = new Retrofit.Builder()
.baseUrl(ConstantApi.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(getOkHttpClient())
.build();

记住 readTimeout 是 0,我使用的是 retrofit 2.1.0。 retrofit 的默认超时时间为 10 秒。我尝试将 readTimeout 设置为 60 秒但没有效果。

关于android - 使用 Retrofit 时出现 SocketTimeOut 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39627988/

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