首页 > 解决方案 > android 凌空超时错误

问题描述

我准备了一个节点 js Web 服务,当我使用以下 URL 测试它时返回 JSON 响应:http://localhost:3000/users?name=ali&password=ali ,它成功返回了我设置的 JSON 响应,所以我确保它正常工作。实际上我正在尝试在 android 中使用这个 web 服务,所以我尝试在 android 中使用 Volley 库获得 JSON 响应,但我得到:com.android.volley.TimeoutError 这是我的 android 代码,我在其中建立连接并发出请求:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String URL = "http://196.2.182.69:3000/users";
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        JsonObjectRequest objectRequest = new JsonObjectRequest(
                Request.Method.GET,
                URL,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.e("Rest Response",response.toString());
                        System.out.println(response.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
               Log.e("Rest Response",error.toString());
                    }
                }
        );
        requestQueue.add(objectRequest);
    }

注意:我用我的 ip 地址更改了 'localhost' 并停用了我的防火墙

标签: javaandroidnode.jsjsonandroid-volley

解决方案


我希望这对你有用。

从真实设备访问 localhost API 时,您的设备必须位于同一网络或 LAN 中。

确保您在清单中添加了 Internet 权限。

DefaultRetryPolicy根据您的要求设置。

 objectRequest.setShouldCache(false);
 objectRequest.setRetryPolicy(new DefaultRetryPolicy(30000,
 DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
 DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

requestQueue.add(objectRequest);在此行之前添加上面的代码。


推荐阅读