Java 改造Android在MySQL中添加新行
在我的项目中,我正在使用改型库,在MySQL数据库中添加一行,我对@POST方法有一些问题 这是我在带有post方法的服务器上的test_retro_post.PHP文件中的PHP代码:Java 改造Android在MySQL中添加新行,java,php,android,mysql,retrofit,Java,Php,Android,Mysql,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 = $_P
<?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);
}
?>
最后,在活动中调用改装:
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);
未添加MySQL数据库中的新行。请告诉我这个代码有什么问题?也许我需要自定义转换器?您的服务器希望将数据作为POST参数发送给它,但您正在尝试将其发送到JSON。您可以更改服务器以接受JSON,也可以更改改型以使用注释发送POST参数。另外,非常确定您希望响应类型为
ResponseBody
,而不是RequestBody
@POST("/test_retro/test_retro_post.php")
Call<ResponseBody> createProd(@Field("id") int id, @Field("name") String name, @Field("price") int price);
@POST(“/test\u retro/test\u retro\u POST.php”)
调用createProd(@Field(“id”)int-id、@Field(“name”)字符串名、@Field(“price”)int-price);
打电话给-
Call<ResponseBody> call = api_post.createProd(3, "prod_3", 300);
Call Call=api_post.createProd(3,“prod_3”,300);
您的服务器希望将数据作为POST参数发送给它,但您正在尝试将其发送到JSON。您可以更改服务器以接受JSON,也可以更改改型以使用注释发送POST参数。另外,非常确定您希望响应类型为ResponseBody
,而不是RequestBody
@POST("/test_retro/test_retro_post.php")
Call<ResponseBody> createProd(@Field("id") int id, @Field("name") String name, @Field("price") int price);
@POST(“/test\u retro/test\u retro\u POST.php”)
调用createProd(@Field(“id”)int-id、@Field(“name”)字符串名、@Field(“price”)int-price);
打电话给-
Call<ResponseBody> call = api_post.createProd(3, "prod_3", 300);
Call Call=api_post.createProd(3,“prod_3”,300);
@POST("/test_retro/test_retro_post.php")
Call<ResponseBody> createProd(@Field("id") int id, @Field("name") String name, @Field("price") int price);
Call<ResponseBody> call = api_post.createProd(3, "prod_3", 300);