我准备了一个 node js webservice,当我用这个 URL 测试它时它返回一个 JSON 响应:http://localhost:3000/users?name=ali&password=ali,它成功返回了我设置的 JSON 响应,所以我确保它正在工作。实际上,我正在尝试在 android 中使用此网络服务,因此我尝试在 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' 并且我停用了我的防火墙
我希望这对你有用。
从真实设备访问 localhost API 时,您的设备必须在同一网络或 LAN 中。
确保您在清单中添加了互联网权限。
DefaultRetryPolicy
根据您的要求进行设置。
objectRequest.setShouldCache(false);
objectRequest.setRetryPolicy(new DefaultRetryPolicy(30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
在此requestQueue.add(objectRequest);
行之前添加上面的代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句