字符串请求发布不显示任何错误

时间:2018-09-11 15:28:52

标签: java android json android-volley

我正在使用字符串请求在Android Studio中发出发布请求,当我调试时,我没有收到任何错误。调试时我没有在代码中得到JSON对象。它会跳过登录请求并结束调试。如果我没有做正确的事情,请尝试并纠正它

这是JSON对象

func stopCaptureSession() {
    self.previewLayer?.removeFromSuperlayer()
    self.previewLayer = nil
    self.captureSession.stopRunning()
    for input in captureSession.inputs {
        self.captureSession.removeInput(input)
    }
    for output in captureSession.outputs {
        self.captureSession.removeOutput(output)
    }
}

这是loginRequest Java类

{"RESPONSECODE":200,
"RESPONSEDATA:[{"id_User":"120","FirstName":"King",
"LastName":"Dosty","Role_Id":"2","Email":"donmister5000@gmail.com","location":null,"Password":"$2y$10$fJJH6qOuhhXaDadHQhZefemBwHPZ3aHid\/WF579DwVJo8XyVGaEN6",
}],"Success":true}

这是登录按钮,用于在活动中单击时发送请求

public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "http://localhost/project/index.php/clientapinew/post_login2";
private Map<String, String> params;
public LoginRequest(String Email,String Password, Response.Listener<String> listener){
    super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
    params = new HashMap<>();
    params.put("Email", Email);
    params.put("Password", Password);
}
@Override
public Map<String, String> getParams(){
    return params;
}
}

这是我调试时的url get和params

  

[] localhost / project / index.php / clientapinew / post_login2     0x59c3b57d正常null     电邮:john@gmail.com     密码:azerty

2 个答案:

答案 0 :(得分:2)

我建议您放弃LoginRequest类,并在LoginActivity中添加此方法:

private void login(final String email, final String password){
        String LOGIN_REQUEST_URL = "http://localhost/project/index.php/clientapinew/post_login2";

        // JSON data
        JSONObject jsonObject = new JSONObject();
        try{
            jsonObject.put("Email", email);
            jsonObject.put("Password", password);
        } catch (JSONException e){
            e.printStackTrace();
        }

        // Json request
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
                LOGIN_REQUEST_URL,
                jsonObject,
                new Response.Listener<JSONObject>(){
                    @Override
                    public void onResponse(JSONObject response){
                        //Toast.makeText(context, "Product successfully added", Toast.LENGTH_SHORT).show();
                        try{
                            //use the response JSONObject now like this log
                            Log.d(TAG, response.getString("Success"));
                            boolean success = response.getBoolean("Success");
                            if (success) {
                                //...
                            }
                        } catch (JSONException e) {
                            System.out.println("Error logging in");
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                if (error instanceof NetworkError) {
                    Toast.makeText(LoginActivity.this, "Can't connect to Internet. Please check your connection.", Toast.LENGTH_LONG).show();
                }
                else if (error instanceof ServerError) {
                    Toast.makeText(LoginActivity.this, "Unable to login. Either the username or password is incorrect.", Toast.LENGTH_LONG).show();
                }
                else if (error instanceof ParseError) {
                    Toast.makeText(LoginActivity.this, "Parsing error. Please try again.", Toast.LENGTH_LONG).show();
                }
                else if (error instanceof NoConnectionError) {
                    Toast.makeText(LoginActivity.this, "Can't connect to internet. Please check your connection.", Toast.LENGTH_LONG).show();
                }
                else if (error instanceof TimeoutError) {
                    Toast.makeText(LoginActivity.this, "Connection timed out. Please check your internet connection.", Toast.LENGTH_LONG).show();
                }

                //Do other stuff if you want
                error.printStackTrace();
            }
        }){

            @Override
            public Map<String,String> getHeaders() throws AuthFailureError {
                Map<String,String> headers = new HashMap<String,String>();
                headers.put("Content-Type", "application/json; charset=utf-8");
                return headers;
            }
        };

        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
                3600,
                0,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        RequestQueueSingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
    }

然后您的onClick应该类似于

loginBtn.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
          String Email = emailEdt.getText().toString();
          String Password = passwordEdt.getText().toString();
          login(Email, Password);
       }

}

创建RequestQueueSingleton.java类,并使用如下代码:

public class RequestQueueSingleton {

private static RequestQueueSingleton mInstance;
private RequestQueue mRequestQueue;

private static Context mCtx;

private RequestQueueSingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();

}

public static synchronized RequestQueueSingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new RequestQueueSingleton(context);
    }
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        // getApplicationContext() is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req) {
    getRequestQueue().add(req);
}
}

答案 1 :(得分:0)

响应中的第一个字符是“>”。尝试运行此行时:

JSONObject jsonResponse = new JSONObject(response);

它在响应中找不到JsonObject,并且您的代码无法正常工作。 我的建议是从您的回复中删除“>”,然后重试。