没有来自Volley JSON请求的回复

时间:2016-01-08 13:50:15

标签: php android web-services

我已经痛苦了几天如何登录我的Android应用程序。我想发送一个带有请求的json对象到我的Webservice。他将检查用户和密码是否正确,并将返回用户信息。我认为web服务还可以,因为当我在我的终端上执行POST时这样:

curl -i -X POST http://bomatec.be/android_login_api/login.php  -d '{"password":"xxxxxx","email":"dddd@gmail.com"}'

我得到了我想要的数据:

{"error":false,"user_id":46,"name":"steven","email":"steven@gmail.com"}

我将在问题的最后发布我的webservice(php)代码。因为我关于我的问题关于SO的关于5个以上的教程和问题,我认为它可能是凭证或权限/认证的问题或其他什么?我仍然无法通过我的Android应用程序获得我的网络服务的响应。

我尝试了两种不同的类型。我现在正在使用这个:

private void checkLogin(final String email, final String password) {
    pDialog.setMessage("Logging in ...");
    showDialog();
    final String URL = "http://bomatec.be/android_login_api/login.php";

    HashMap<String, String> params = new HashMap<String, String>();
    params.put("email", email);
    params.put("password", password);

    JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    String responses = response.toString();
                    try {
                        VolleyLog.v("Response:%n %s", response.toString(4));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.e("Error: ", error.getMessage());
        }
    });
    ApplicationController.getInstance().addToRequestQueue(req);
}

这是 ApplicationController

package info.androidhive.loginandregistration.helper;

/**
 * Created by stevengerrits on 7/01/16.
 */
import android.app.Application;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.android.volley.Request;
import com.android.volley.VolleyLog;
import android.text.TextUtils;

public class ApplicationController extends Application {

    /**
     * Log or request TAG
     */
    public static final String TAG = "VolleyPatterns";

    /**
     * Global request queue for Volley
     */
    private RequestQueue mRequestQueue;

    /**
     * A singleton instance of the application class for easy access in other places
     */
    private static ApplicationController sInstance;

    @Override
    public void onCreate() {
        super.onCreate();

        // initialize the singleton
        sInstance = this;
    }

    /**
     * @return ApplicationController singleton instance
     */
    public static synchronized ApplicationController getInstance() {
        return sInstance;
    }

    /**
     * @return The Volley Request queue, the queue will be created if it is null
     */
    public RequestQueue getRequestQueue() {
        // lazy initialize the request queue, the queue instance will be
        // created when it is accessed for the first time
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }


    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);

        VolleyLog.d("Adding request to queue: %s", req.getUrl());

        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        // set the default tag if tag is empty
        req.setTag(TAG);

        getRequestQueue().add(req);
    }

    /**
     * Cancels all pending requests by the specified TAG, it is important
     * to specify a TAG so that the pending/ongoing requests can be cancelled.
     *
     * @param tag
     */
    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

我也尝试过这里提到的helperclass(这是我的旧代码):Volley JsonObjectRequest Post request not working

但这也没有奏效。代码:

private void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        //String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        HashMap<String, String> params = new HashMap<String, String>();
        params.put("email", email);
        params.put("password", password);

        JsonObjectRequest req = new JsonObjectRequest("http://bomatec.be/android_login_api/login.php", new JSONObject(params),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            VolleyLog.v("Response:%n %s", response.toString(4));
                            JSONObject jObj = response;
                            //hideDialog();

                            try {
                                boolean error = jObj.getBoolean("error");

                                // Check for error node in json
                                if (!error) {
                                    // user successfully logged in
                                    // Create login session
                                    session.setLogin(true);

                                    // Now store the user in SQLite
                                    String uid = jObj.getString("uid");

                                    JSONObject user = jObj.getJSONObject("user");
                                    String name = user.getString("name");
                                    String email = user.getString("email");
                                    String userid = user.getString("user_id");
                                    // Inserting row in users table

                                    // Launch main activity

                                    //Intent intent = new Intent(LoginActivity.class,MainActivity.class);
                                    //startActivity(intent);
                                    //finish();
                                } else {
                                    // Error in login. Get the error message
                                    String errorMsg = jObj.getString("error_msg");
                                    Toast.makeText(getApplicationContext(),
                                          errorMsg, Toast.LENGTH_LONG).show();
                                }
                            } catch (JSONException e) {
                                // JSON error
                                e.printStackTrace();
                                //Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                        public void onErrorResponse(VolleyError error) {
                        VolleyLog.e("Error: ", error.getMessage());
                }
            });
        ApplicationController.getInstance().addToRequestQueue(req);
    }

这是 webservice PHP代码

<?php

/**
 * @author Ravi Tamada
 * @link http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/ Complete tutorial
 */
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// json response array
$response = array("error" => FALSE);

//function using_json() {
    $json = file_get_contents('php://input');
    $obj = json_decode($json);
//echo json_encode(array('json'=>$obj));
    $email = $obj->email;
    $password = $obj->password;
    // get the user by email and password
    echo $email;
    echo $password;
    $auth = $db->resolve_user_login($email, $password);
    $user_name = $db->get_user_name($email);
    $user_id = $db->get_user_id($email);


    if ($auth) {
        echo "   in auth ::: ";
        // use is found
        $response["error"] = FALSE;
        $response["user_id"] = $user_id;
        $response["name"] = $user_name;
        $response["email"] = $email;
        echo json_encode($response);
    } else {
        echo "    in else   :::    ";
        // user is not found with the credentials
        $response["error"] = TRUE;
        $response["error_msg"] = "Login credentials are wrong. Please try again!";
        echo json_encode($response);
    }
?>

这是我的调试器数据。所以你可以看到我的请求对象 (忽略/ login.php之后,这只是一个测试,如果它适用于/)

[IMG] http://i63.tinypic.com/155mjba.png[/IMG]

1 个答案:

答案 0 :(得分:0)

试试这段代码,我没有凭据,所以我无法获得输出,但你可以。

我正在使用此库common-io,可以像这样导入

compile 'org.apache.commons:commons-io:1.3.2'

以下是运行AsyncTask

的代码
private class MyTask extends AsyncTask<Void, Void, Void>{

    @Override
    protected Void doInBackground(Void... params) {

        try {
            URL url = new URL("http://www.bomatec.be/android_login_api/login.php");

            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.connect();

            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("email", "dddd@gmail.com");
            jsonObject.addProperty("password", "password");

            DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
            wr.writeBytes(jsonObject.toString());
            wr.flush();
            wr.close();

            Log.d("TAG",""+ IOUtils.toString(httpURLConnection.getInputStream()));


        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
  

输出

in else   :::    {"error":true,"error_msg":"Login credentials are wrong. Please try again!  da was de mail, dees is het pass "}