我的Android应用程序中的请求出现超时错误。我已经设置了重试策略,但它没有解决问题。在我的模拟器上测试时它没有错误,但是当使用真实设备进行测试时会出现超时错误。
public void makeRequest(final String user, final String cred)
{
String url = "http://10.0.2.2:8888/map/api/login";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response)
{
try
{
JSONObject jsonResponse = new JSONObject(response);
String status = jsonResponse.getString("status");
String token = jsonResponse.getString("token");
if(status.equalsIgnoreCase("error"))
{
Snackbar.make(findViewById(R.id.myCoordinatorLayout), jsonResponse.getString("message"), Snackbar.LENGTH_LONG).show();
}
else if (status.equalsIgnoreCase("success"))
{
System.out.println(jsonResponse);
Intent loader = new Intent(home.this,webViewActivity.class);
loader.putExtra(EXTRA_MESSAGE,token);
startActivity(loader);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
error.printStackTrace();
}
}
){
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
params.put("portal[username]", user);
params.put("portal[password]", cred);
params.put("portal[From]","web");
return params;
}
};
postRequest.setRetryPolicy(new DefaultRetryPolicy(
7000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(getApplicationContext()).add(postRequest);
}
我得到的错误低于
08-18 12:42:46.341 16112-16112/com.mobile.map.map_mobile W/System.err: com.android.volley.TimeoutError
08-18 12:42:46.341 16112-16112/com.mobile.map.map_mobile W/System.err: at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:141)
08-18 12:42:46.341 16112-16112/com.mobile.map.map_mobile W/System.err: at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)
答案 0 :(得分:0)
您可以检查不同的设备和不同的网络。如果它不起作用,请检查邮递员的响应时间是否超过2500毫秒(凌空默认超时),在DefaultRetryPolicy.class中增加凌空的默认超时
答案 1 :(得分:0)
我假设你的Key值对是Body。
JSONObject params = new JSONObject();
try {
params.put("portal[username]", user);
params.put("portal[password]", cred);
params.put("portal[From]","web");
} catch (JSONException e) {
// Do something
}
Response.Listener<JSONObject> jsonObjectListener = new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// Response here
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Error here
}
};
String url = "http://10.0.2.2:8888/map/api/login";
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, params,
jsonObjectListener, errorListener);
Volley.newRequestQueue(getApplicationContext()).add(jsonRequest);