【发布时间】:2018-07-05 21:22:54
【问题描述】:
我正在重构我的应用程序以使用Retrofit 2,我能够使我的所有GET requests 正常,但我不明白如何使POST requests。
我有这个例外:
java.lang.IllegalStateException: 应为 BEGIN_OBJECT 但为 STRING 在第 1 行第 1 列路径 $e 此处
我知道那个异常是什么意思,很简单。我的问题是我无法将我的 PHP 文件更改为期望字符串,或者更改 java 类以发送对象。
我对 PHP 了解甚少,所以我更喜欢更改我的 java 类。
我想到的不是发送我的 java pojo 类,而是可以创建一个 JSONObject 并将其发送到 PHP。
但是,我对 PHP 文件或我想到的方法不是很有信心。我想告诉我这是否是一个可能的解决方案,或者 PHP 代码中是否有问题,这就是当前无法正常工作的原因。
以下是课程:
<?php
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$dbh = $db->connect(); // here you get the connection
$name = $_POST['name'];
$breed = $_POST['breed'];
$type = $_POST['type'];
$description = $_POST['description'];
$pictures = $_POST['pictures'];
$location = $_POST['location'];
$locality = $_POST['locality'];
$userid = $_POST['userid'];
$query = "INSERT INTO lost_pets (name, breed, type, description, pictures, location,locality, userid) VALUES('$name', '$breed', '$type', '$description', '$pictures', '$location', '$locality','$userid')";
$stmt = $dbh->prepare($query);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':breed', $breed, PDO::PARAM_STR);
$stmt->bindParam(':type', $type, PDO::PARAM_STR);
$stmt->bindParam(':description', $description, PDO::PARAM_STR);
$stmt->bindParam(':pictures', $pictures, PDO::PARAM_STR);
$stmt->bindParam(':location', $location, PDO::PARAM_STR);
$stmt->bindParam(':locality', $locality, PDO::PARAM_STR);
$stmt->bindParam(':userid', $userid, PDO::PARAM_STR);
$dbh = $stmt->execute(array(":name"=>$name,":breed"=>$breed,":type"=>$type,":description"=>$description,
":pictures"=>$pictures,":location"=>$location, ":locality"=>$locality, ":userid"=>$userid));
?>
Java 接口:
@POST("post_lost_pet.php")
Call<Lost> postLost(@Body Lost lost);
postLost 方法:
public void postLost(Lost pet, final IClient client){
Call<Lost> call = retrofitInit().postLost(pet);
call.enqueue(new Callback<Lost>() {
@Override
public void onResponse(Call<Lost> call, Response<Lost> response) {
System.out.println(response.raw());
client.lostCallback();
}
@Override
public void onFailure(Call<Lost> call, Throwable t) {
client.lostFailure(t.toString());
}
});
POJO:
public class Lost extends Pet {
public Lost(String name, String breed, String type, String description, String pictures, String location, String locality, String userid) {
super(name, breed, type, pictures, description, location, locality, userid);
}
public void setLocality(String locality){
super.setLocality(locality);
}
public void setName(String name) {
super.setName(name);
}
}
【问题讨论】:
-
错误信息表明您的 PHP 代码没有返回有效的 JSON 对象。由于您没有输出任何内容,我的猜测是您收到了一条错误消息,或者 Retrofit 期望至少返回一些数据(而不是文本“null”或类似的)。
标签: java php android pdo retrofit