如何获取服务器忙的JSON状态?

时间:2017-07-04 17:25:03

标签: java android json

我的JSON代码:

Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonResponse = new JSONObject(response);
                            int success = jsonResponse.getInt("success");

                            if (success == 0) {

                            }
                            if (success == 1) { 

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };
                nRequest nRequest = new nRequest(edtTextReg.getText().toString(), responseListener);
                RequestQueue queue = Volley.newRequestQueue(login.this);
                queue.add(nRequest);

我怎样才能找到JSON给我状态的方式&#34;服务器忙碌&#34;?繁忙意味着例如:成千上万的人使用我的服务器。

2 个答案:

答案 0 :(得分:0)

如果你的服务器很忙,你不希望它花时间渲染JSON,而且,如果服务器负载在你的脑海中,你最终可能会把你的应用程序放在负载均衡器之后,那些通常一无所知JSON。

处理这种情况的正确方法是解析正确的HTTP状态代码,通常为429,请参阅this answer

要访问状态代码,您的onResponse应如下所示:

@Override    
public void onSuccess(int statusCode, String content) {
}

答案 1 :(得分:0)

服务器重载的Http状态代码为503.

503 - 服务不可用 在极忙的服务器上最常见到503状态代码,它表示由于服务器过载,服务器无法完成请求。

  

所以你的代码应该是这样的:

                @Override

                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);

                 int status = jsonResponse.getStatusLine().getStatusCode();
                      int success = jsonResponse.getInt("success");
                        if (status == 503) {
                          // 
                        }

                        if (success == 0) {

                        }
                        if (success == 1) { 

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