Call Firebase function from Java via POST

Viewed 62

So I've got this TypeScript function which writes document to firestore

    exports.register = functions.https.onRequest((req:any, res:any) => {
    if (req.method === 'PUT') {
        res.status(403).send('Forbidden!');
        return;
    }   
    cors(req, res, () => {
        const name = req.query.name;
        //validations
        if (!name) {
            res.status(200).send("Please enter name.");
            return;
        }
        //Other input validations....
    
        const vkey = Math.random()*1000000000000000;
        
        //check if user already exists in firestore
        const userRef = admin.firestore().collection('users')

        let userExists;
        userRef.where('email', '==', email).get()
        .then((snapshot: { size: any; }) => {
            userExists = snapshot.size;
            console.log(`user by email query size ${userExists}`);
            //send error if user exists
            if(userExists && userExists > 0){
                res.status(200).send("Account with the same email exists");
                return;
            }
            //add user to database
            admin.firestore().collection('users').add({
                name: name,
                email: email,
                password: password,
                user: user,
                vkey: vkey,
                verified: 0,
                token: 0
            }).then((ref: { id: any; }) => {
                console.log('add user account', ref.id);
                res.status(200).send("Registered");
                return; 
            });             

        })
        .catch((err: any) => {
            console.log('error getting user by email', err);
            res.status(200).send("System error, please try again.");
        });


    });
});

And I need to call this function from my java code via POST request. I already did so via GET but the data I have to send is larger than GET can handle.(I know that register function is working correctly since I'm getting responses and when testing with GET and less data to send it writes the document to firestore no problem) My current code to achieve POST looks like this:

public class UtilsUpdateUser extends AsyncTask<String,Void,String> {
        @Override
        protected String doInBackground(String... urls) {
            try {

                String jsonString = Utils.userToString(Utils.USER);

                String data = URLEncoder.encode("name", "UTF-8") + "=" +
                        URLEncoder.encode(usernameString, "UTF-8");
                data += "&" + URLEncoder.encode("password", "UTF-8") + "=" +
                        URLEncoder.encode(Utils.PASSWORD, "UTF-8");
                data += "&" + URLEncoder.encode("user", "UTF-8") + "=" +
                        URLEncoder.encode(jsonString, "UTF-8");
                data += "&" + URLEncoder.encode("email", "UTF-8") + "=" +
                        URLEncoder.encode(emailString, "UTF-8");

                URL url = new URL(urls[0]);
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.flush();
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                return sb.toString();
            } catch (Exception e) {
                return "Internet";
            }
        }
        @Override
        protected void onPostExecute(String s) {
            Log.i("MyData",s);
        }
    }

But this code always results in "Please enter name." Any help is greatly appreciated.

1 Answers

The POST call was right the problem was that in the cloud function I used req.query.VARIABLE_NAME; this would be fine for GET put in case of POST it;s req.body.VARIABLE_NAME;

Related