【问题标题】:Sending Firebase token to own server not working将 Firebase 令牌发送到自己的服务器不起作用
【发布时间】:2019-07-11 23:05:05
【问题描述】:

我正在尝试将令牌发送到 mySQL 数据库以存储在那里。我在 onNewToken() 的 myFirebaseMessagingService 类中调用以下方法,但没有任何反应。该功能正在运行,但令牌和用户名未存储在数据库中。

  private void sendRegistrationToServer(String token) {
        JSONObject request = new JSONObject();
        try {
            //Populate the request parameters
            request.put(KEY_USERNAME, "testUser");
            request.put(KEY_TOKEN, token);
            Log.d("test","request: " + request.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest jsArrayRequest = new JsonObjectRequest
                (Request.Method.POST, submitToken_url, request, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.v("test","This is php response");
                        try {
                            //Check if user got registered successfully
                            if (response.getInt(KEY_STATUS) == 0) {
                                //Set the user session
                               Log.v("test","Token Stored Successfully" + KEY_STATUS);

                            } else if (response.getInt(KEY_STATUS) != 0) {
                                Log.v("test","Token Storing Failed" + KEY_STATUS);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {

                        //Display error message whenever an error occurs
                        Toast.makeText(getApplicationContext(),
                                error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

        // Access the RequestQueue through your singleton class.
        MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
    }

这也是我的 php 文件:

<?php
$response = array();
include 'db/db_connect.php'; 
//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array
//Check for Mandatory parameters
if(isset($input['username']) && isset($input['token']) ){
    $username = $input['username'];
    $token = $input['token'];
        //Query to register new user
        $insertQuery  = "INSERT INTO firebaseUser(username,token) VALUES (?,?)";
        if($stmt = $con->prepare($insertQuery)){
            $stmt->bind_param("ssss",$username,$token);
            $stmt->execute();
            $response["status"] = 0;
            $response["message"] = "User Token Stored";
            $stmt->close();
        }
}

echo json_encode($response);
?>

我添加了一个日志,现在出现了这个错误org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject

我的单例类:

import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class MySingleton {
    private static MySingleton mInstance;
private static Context mCtx;
private RequestQueue mRequestQueue;

private MySingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();
}

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

private 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);
}

}

【问题讨论】:

  • $stmt-&gt;bind_param("ssss",$username,$token); 这应该会抛出一个错误信息,因为你只有2个参数,你只需要2个数据类型"ss"
  • 这里的帖子告诉你在 PHP 中启用错误报告以便更好地调试stackoverflow.com/questions/1053424/…
  • @catcon 谢谢。我不知道我是怎么错过的。我将其更改为“ss”,但仍然没有存储令牌。我的java方法正确吗?我还缺少其他东西吗?
  • 你能发一下这个MySingleton类吗?
  • @JonathasNascimento 已更新。另外,我在SignUp函数中使用了类似的方法,效果很好。

标签: php android mysql firebase


【解决方案1】:

解决了。我已将我的 php 文件更新为以下内容:

<?php
$response = array();
include 'db/db_connect.php';

//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array

//Check for Mandatory parameters
if(isset($input['username']) && isset($input['token'])){
$username = $input['username'];
$token = $input['token'];


    //Query to register new user
    $insertQuery  = "INSERT INTO firebaseUsers(username, token) VALUES (?,?)";
    if($stmt = $con->prepare($insertQuery)){
        $stmt->bind_param("ss",$username,$token);
        $stmt->execute();
        $response["status"] = 0;
        $response["message"] = "Token Saved";
        $stmt->close();
    }

}
else{
$response["status"] = 1;
}
echo json_encode($response);
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-15
    • 2019-11-13
    • 2016-11-08
    • 2017-11-08
    • 2011-11-20
    • 2020-08-03
    • 1970-01-01
    • 2016-09-06
    相关资源
    最近更新 更多