OkHttp3返回超时异常 [英] OkHttp3 is returning timeout exception

查看:404
本文介绍了OkHttp3返回超时异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using okhttp3 as a networking library and Node-mongo as a back-end service.Sometimes when my app starts it shows timeout exception and when I close app and start it again then it fetches data from the server.There is no error in app but I want to know why timeout exception is showing.

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

Below is my code in which I am showing data in listview.

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;

  }
}

我该如何解决?

推荐答案

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

Server timeout will happen if your server is slow or your server's default timeout will be very less.

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

in this case you can set time-out for your requests like below

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

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

if you are using OkHttp3 then you can use the Builder to achieve this task like below.

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

这篇关于OkHttp3返回超时异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆