首页 > 解决方案 > PHP API 不能与改造/gson 结合使用

问题描述

我无法让我的 rest API 使用改造/gson 处理来自我的 android 应用程序的 POST 请求。支持 REST API 的功能是将非常基本的 JSON 解码,在其上运行一系列 SQL 查询,然后将格式化的 JSON 数据返回给应用程序。

我知道问题不在于 API 逻辑,当我将传入的 JSON 数据硬编码或将 JSON 响应硬编码到 PHP 中时,API 工作正常。当我需要使用来自应用程序的 POST 请求传递 JSON 时,问题就开始了。我总是得到以下例外:FATAL EXCEPTION: DefaultDispatcher-worker-1或者FATAL EXCEPTION: DefaultDispatcher-worker-2传入的 JSON 来自应用程序。

我尝试了 3 种接收传入 JSON 的方法。第一个是使用$jsonobj = http_get_request_body();函数,第二个是$jsonobj = file_get_contents('php://input');,第三个是 $jsonobj = $_POST['code'];最后一个很有趣。我不知道['here']maters 中有什么或名称是什么,所以我可以使用它。我已经尝试在这里更改['text']几次,但没有成功。

在我们继续之前,这里是我的 PHP 脚本的概述。

//database config here.

if($_SERVER["REQUEST_METHOD"] == "POST"){
    //method of reciving JSON here.
    $obj = json_decode($jsonobj);

    //SQL logic here.
    echo json_encode($return);
}

如果不适用于 JSON 接收器,则此方法有效。

还有一个很好的机会,我什至根本不发送 JSON,更不用说有效的 JSON。我知道有记录出站 JSON 的方法,但对于我的生活,我无法让它们工作。所以在这里我将发布一些我的android代码。

我的 API 接口

interface API {
    @POST("posttest.php")
    suspend fun postit(@Body post: String): Phone
}

我在这种情况下使用所说的接口

val api = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(API::class.java)

    GlobalScope.launch(Dispatchers.IO) {
        val response = api.postit(test)

        try {
               //logic
        }catch (e: Exception){
            //error handling
        }
    }

}

我想从房间数据库中提取 JSON,但我还没有这样做,所以我只对 JSON 进行了硬编码;它看起来像这样。

    private var test = "[\"text1\", \"text2\", \"text3\"]"

感谢您的时间。

标签: phpandroidjsonkotlinretrofit2

解决方案


以下是仅用于与 API 建立应用程序连接的代码。您将根据自己的需求进行调整的所有其他内容(改造请求、响应、json 编码)

在 Android 应用程序中关注日志

我强烈建议您不要在没有数据验证的情况下查询数据库并使用 PDO

最好为 api 使用一些 php 框架,如 Slim、Laravel、Lumen

您可以使用最常用的类型之一发布请求:

  • application/x-www-form-urlencoded = 参数编码
  • application/json = 发送 json 数据 //用于你的情况
  • multipart/form-data = 像图片这样的文件

你的 PHP 脚本应该是这样的

if($_SERVER["REQUEST_METHOD"] == "POST"){
    
    //TODO this is only example to get and return json data
    
    $jsonobj = file_get_contents('php://input');
    $json = json_decode($jsonobj);
    
    $response = array(
        "raw" => $jsonobj,
        "json" => $json
    );
    
    echo json_encode($response);
}else{
    //Send a 405 Method Not Allowed
    http_response_code(405);
    exit;
}

接口API

interface API {
    @POST("posttest.php")
    suspend fun postIt(@Body requestBody: RequestBody): Response<ResponseBody>
}

和主要

val api = Retrofit.Builder()
                .baseUrl(BASE_URL)
                //.addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(API::class.java);

        val test = "[\"text1\", \"text2\", \"text3\"]";  //hardcoded by you
        val requestBody = test.toRequestBody("application/json".toMediaTypeOrNull())

        GlobalScope.launch(Dispatchers.IO) {
            val response = api.postIt(requestBody)
            //withContext(Dispatchers.Main) {
                try {
                    if (response.isSuccessful) {
                        Log.i("RESPONSE", "DATA: " + response.body()?.string());
                    } else {
                        Log.i("RESPONSE", "ERROR: " + response.errorBody()?.string());
                    }

                    Log.i("RESPONSE", "RAW: " + response.raw());
                } catch (e: Exception) {
                    e.printStackTrace();
                    //error handling
                }
            //}
        }

推荐阅读