【发布时间】:2018-10-16 00:39:46
【问题描述】:
我正在使用 PHP Slim 框架为 Android 应用程序构建 REST API。
我在应用程序中发布正文,它运行良好并将数据添加到 MySQL。但我的反应有问题。
我的响应 JSON 模型很简单;
{success:'yes'}
当我在添加数据后尝试获得响应时,Retrofit 会使用 onFailure 方法。但添加数据效果很好。我不知道我错过了哪里。这是我的代码;
PHP Slim 框架文件
$response->withHeader('Content-Type', 'application/json');
$response->getBody()->write("{success:'yes'}");
return $response;
} catch (PDOException $e) {
echo '{"error": {"text": ' . $e->getMessage() . '}';
}
Android 响应模型
public class Response_Success {
@SerializedName("success")
@Expose
String success;
public Response_Success(String success) {
this.success = success;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
接口类
public interface API_Service {
@Headers("content-type: application/json")
@POST("api/user/add")
Call<Response_Success> addFacebookUser(@Body UserFacebook userFacebook);}
MainActivity 中的 API 调用
API_Service service = Client.getRetrofitInstance().create(API_Service.class);
Call<Response_Success> userFacebookCall = service.addFacebookUser(userNew);
userFacebookCall.enqueue(new Callback<Response_Success>() {
@Override
public void onResponse(Call<Response_Success> call, Response<Response_Success> response) {
Toast.makeText(MainActivity.this, ""+response.body().getSuccess(), Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<Response_Success> call, Throwable t) {
Toast.makeText(MainActivity.this, "was wrong", Toast.LENGTH_SHORT).show();
}
});
android studio 中的调试模式;我得到 MaltFormedJsonException,但我在 try catch 中添加了该异常。
【问题讨论】:
-
你可以做 -
return $response->withJson(array('success' => 'yes'));(slimframework.com/docs/v3/objects/response.html#returning-json) -
不错的选择,非常感谢!
标签: java php android retrofit slim