OkHttp3返回超时异常

时间:2018-11-02 06:47:48

标签: android android-studio

我使用okhttp3作为网络库,使用Node-mongo作为后端服务,有时我的应用程序启动时显示超时异常,当我关闭应用程序并再次启动时,它从服务器获取数据。应用程序中没有错误,但我想知道为什么显示超时异常。

下面是我在列表视图中显示数据的代码。

MainActivity.java

public class Activity2 extends AppCompatActivity {

ListView listView;
List<Data> places;

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

    listView  = findViewById(R.id.listView);
    places = new ArrayList<>();

    final ProgressDialog prg = new ProgressDialog(Activity2.this);
    prg.setMessage("Loading...");
    prg.show();

    Log.d("OnCreate","Oncreate started");

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder().url("https://tiffino.herokuapp.com/test").build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, final IOException e) {

            prg.dismiss();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),""+e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            });
        }

        @Override
        public void onResponse(Call call, final Response response) throws IOException {

            prg.dismiss();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    try {
                        JSONArray arr = new JSONArray(response.body().string());

                        for(int i = 0;i < arr.length();i++){

                            JSONObject obj = arr.getJSONObject(i);

                            String str1 = obj.getString("Name");

                            Data data = new Data(str1);

                            places.add(data);

                        }

                        PlacesAdapter adapter=  new PlacesAdapter(places,getApplicationContext());
                        listView.setAdapter(adapter);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

    });

   }
} 

PlacesAdapter.java

public class PlacesAdapter extends ArrayAdapter<Data> {

private List<Data>  places;
private Context ctx;

public PlacesAdapter( List<Data> places, Context ctx) {
    super(ctx,R.layout.places_row,places);
    this.places = places;
    this.ctx = ctx;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

    LayoutInflater inflater = LayoutInflater.from(ctx);

    View listView = inflater.inflate(R.layout.places_row,null,true);

    TextView txt = listView.findViewById(R.id.txt);

    Data data = places.get(position);

    txt.setText(data.getPlace());

    return listView;

  }
}

我该如何解决?

1 个答案:

答案 0 :(得分:2)

如果您的服务器运行缓慢或服务器的默认超时时间会非常短,则会发生服务器超时。

在这种情况下,您可以为请求设置超时,如下所示:

client.setConnectTimeout(35, TimeUnit.SECONDS); //change timeout according to your server needs
client.setReadTimeout(35, TimeUnit.SECONDS);
client.setWriteTimeout(35, TimeUnit.SECONDS);

如果您使用的是OkHttp3,则可以使用Builder来完成此任务,如下所示。

client = new OkHttpClient.Builder()
        .connectTimeout(30, TimeUnit.SECONDS)
        .writeTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build();