这个问题在这里已有答案:
我正在Flask中编写一个API,它接收用户详细信息并将其插入数据库。我在Android上使用Retrofit来处理这个API。一切正常,但不知何故用户输入值没有传递给API。数据库使用空值更新,而不是用户提供的值。
如果我使用Postman在URL中手动添加参数值,即(hostname / add_user?username =“abc”&password =“abc”....),数据库会更新
我是新手改造的,所以我不知道我到底在哪里错了!
Flask API:
@app.route('/add_user', methods=['POST'])
def add_user():
username = request.args.get('username')
password = request.args.get('password')
name = request.args.get('name')
age = request.args.get('age')
gender = request.args.get('gender')
cnumber = request.args.get('cnumber')
address = request.args.get('address')
city_id = request.args.get('city_id')
email = request.args.get('email')
t = (username,password,name,age,gender,cnumber,address,city_id,email) #Storing all the received values in tuple
cur = mysql.connection.cursor()
cur.execute("INSERT INTO users (username,password,name,age,gender,contactnumber,address,city_id,email) values (%s,%s,%s,%s,%s,%s,%s,%s,%s)", t)
mysql.connection.commit()
resp = jsonify("User added successfully")
resp.status_code = 200
resp.headers['Success'] = 'Success'
return resp
JAVA代码:
Call<ResponseBody> call = API_Client.getInstance().getAPI().add_user(username.getText().toString(), password.getText().toString(), name.getText().toString(), Integer.parseInt(age.getText().toString()), gender.getSelectedItem().toString(), cnumber.getText().toString(), address.getText().toString(), city.getId(), email.getText().toString());
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String s = response.body().string();
Toast.makeText(UserSignup.this, s, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(UserSignup.this, t.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
API接口:
@FormUrlEncoded
@POST("add_user")
Call<ResponseBody> add_user(
@Field("username") String username,
@Field("password") String password,
@Field("name") String name,
@Field("age") int age,
@Field("gender") String gender,
@Field("cnumber") String cnumber,
@Field("address") String address,
@Field("city_id") int city_id,
@Field("email") String email
);
}
我认为这必须是GET
请求hostname/add_user?username="abc"&password="abc"
。将您的API接口更改为此或仅使用@Field
替换@Query
@GET("add_user")
Call<ResponseBody> add_user(
@Query("username") String username,
@Query("password") String password,
@Query("name") String name,
@Query("age") int age,
@Query("gender") String gender,
@Query("cnumber") String cnumber,
@Query("address") String address,
@Query("city_id") int city_id,
@Query("email") String email
);