我正在Flask中编写一个API,该API接收用户详细信息并将其插入数据库中。我正在Android上使用Retrofit来使用此API。一切工作正常,但是用户输入值未以某种方式传递给API。数据库将使用空值而不是用户提供的值进行更新。
如果我使用邮递员在URL中手动添加参数值,则数据库确实会更新,即(主机名/ add_user?username =“ abc”&password =“ abc” ....)
我是改造的新手,所以我不知道哪里出了问题!
烧瓶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
);
}
答案 0 :(得分:0)
我认为这必须是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
);