英文:
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) => {
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
得分: 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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论