我在我的项目中使用 Retrofit 库,在 MySQL 数据库中添加一行,我在 @POST方法方面遇到了一些问题
这是我在带有POST方法的服务器上的文件 test_retro_post.php 中的PHP代码:
<?php
$response = array();
if (isset($_POST['id']) && isset($_POST['name']) && isset($_POST['price'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$price = $_POST['price'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO test_retro(id, name, price) VALUES('$id', '$name', '$price')");
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}
?>
使用自定义JSONparser发送通常的HttpRequest,一切正常:
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", id));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
// getting JSON Object
// url_create_product is URL to my PHP file with POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
但使用Retrofit时出了点问题。未添加新行。 这是 Api_post.java 接口,改造@POST方法:
public interface Api_post{
@POST("/test_retro/test_retro_post.php")
Call<RequestBody> createProd(@Body RequestBody body);
我的RequestBody类(RequestBody.java):
public class RequestBody{
int id;
String name;
int price;
RequestBody(int id, String name, int price){
this.id=id;
this.name = name;
this.price = price;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
最后在活动中调用Retrofit:
Retrofit restAdapter = new Retrofit.Builder()
.baseUrl(Url.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api_post api_post = restAdapter.create(Api_post.java);
Call<RequestBody> call = api_post.createProd(new RequestBody(3, "prod_3", 300);
然后在AsyncTask中执行此调用:
call.execute();
MySQL DB中的新行没有添加。请告诉我这段代码有什么问题?也许我需要自定义转换器?