调用 Firebase 函数从 Java 通过 POST 请求方式

huangapple go评论71阅读模式
英文:

Call Firebase function from Java via POST

问题

以下是您的代码翻译部分:

TypeScript 函数示例:

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;
        // 验证
        if (!name) {
            res.status(200).send("Please enter name.");
            return;
        }
        // 其他输入验证...

        const vkey = Math.random() * 1000000000000000;

        // 检查用户是否已存在于 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}`);
            // 如果用户存在则发送错误
            if (userExists && userExists > 0) {
                res.status(200).send("Account with the same email exists");
                return;
            }
            // 添加用户到数据库
            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.");
        });
    });
});

Java 代码示例:

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

如果您有关于代码的进一步问题,欢迎提问。

英文:

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

    exports.register = functions.https.onRequest((req:any, res:any) =&gt; {
if (req.method === &#39;PUT&#39;) {
res.status(403).send(&#39;Forbidden!&#39;);
return;
}	
cors(req, res, () =&gt; {
const name = req.query.name;
//validations
if (!name) {
res.status(200).send(&quot;Please enter name.&quot;);
return;
}
//Other input validations....
const vkey = Math.random()*1000000000000000;
//check if user already exists in firestore
const userRef = admin.firestore().collection(&#39;users&#39;)
let userExists;
userRef.where(&#39;email&#39;, &#39;==&#39;, email).get()
.then((snapshot: { size: any; }) =&gt; {
userExists = snapshot.size;
console.log(`user by email query size ${userExists}`);
//send error if user exists
if(userExists &amp;&amp; userExists &gt; 0){
res.status(200).send(&quot;Account with the same email exists&quot;);
return;
}
//add user to database
admin.firestore().collection(&#39;users&#39;).add({
name: name,
email: email,
password: password,
user: user,
vkey: vkey,
verified: 0,
token: 0
}).then((ref: { id: any; }) =&gt; {
console.log(&#39;add user account&#39;, ref.id);
res.status(200).send(&quot;Registered&quot;);
return;	
});      	   	
})
.catch((err: any) =&gt; {
console.log(&#39;error getting user by email&#39;, err);
res.status(200).send(&quot;System error, please try again.&quot;);
});
});
});

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&lt;String,Void,String&gt; {
@Override
protected String doInBackground(String... urls) {
try {
String jsonString = Utils.userToString(Utils.USER);
String data = URLEncoder.encode(&quot;name&quot;, &quot;UTF-8&quot;) + &quot;=&quot; +
URLEncoder.encode(usernameString, &quot;UTF-8&quot;);
data += &quot;&amp;&quot; + URLEncoder.encode(&quot;password&quot;, &quot;UTF-8&quot;) + &quot;=&quot; +
URLEncoder.encode(Utils.PASSWORD, &quot;UTF-8&quot;);
data += &quot;&amp;&quot; + URLEncoder.encode(&quot;user&quot;, &quot;UTF-8&quot;) + &quot;=&quot; +
URLEncoder.encode(jsonString, &quot;UTF-8&quot;);
data += &quot;&amp;&quot; + URLEncoder.encode(&quot;email&quot;, &quot;UTF-8&quot;) + &quot;=&quot; +
URLEncoder.encode(emailString, &quot;UTF-8&quot;);
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 &quot;Internet&quot;;
}
}
@Override
protected void onPostExecute(String s) {
Log.i(&quot;MyData&quot;,s);
}
}

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

答案1

得分: 0

POST调用没问题,问题在于在云函数中我使用了req.query.VARIABLE_NAME;,这对于GET来说没问题,但在POST情况下应该使用req.body.VARIABLE_NAME;

英文:

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;

huangapple
  • 本文由 发表于 2020年7月27日 18:07:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63113070.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定