首页 > 解决方案 > Android:发送问题(在 Kotlin 中使用 Retrofit)或从 php 接收 json 文件

问题描述

我在 Kotlin 中开发和 android 应用程序,我遇到了一个问题,用 'POST' 发送一个 json 对象。

问题是我将以下内容作为回应:

Post{username='null',pass='null',latitude=null,longitude=null,id=2}

正如我们得出的结论,因为上述“消息”中的id=2 json 数据不为空,但字段为空。所以问题是我无法正确解码和读取 json 数据,并且在上面的消息中可以看到,因为用户名、通行证、纬度、经度为空。发送上述消息的 php 如下,我在互联网上找到它(http://eosrei.net/articles/2011/12/basic-json-requestresponse-php)并对其进行了修改。

<?php
if (_REQUEST['json']) {
    $data = file_get_contents('php://input');
    $json_data = json_decode($data , true);
    if (is_null($json_data)) {  
        $response = array(
            'username' => json_data['username'],
            'pass' => json_data['pass'],
            'latitude' => json_data['latitude'],
            'longitude' => json_data['longitude'],
            'id' => 1
            );
    }
    else {
        $response = array(
            'username' => $json_data->username,
            'pass' => $json_data->pass,
            'latitude' => $json_data->latitude,
            'longitude' => $json_data->longitude,
            'id' => 2
            );  
    }
}
else {
        $response = array(
            'type' => 'error',
            'tsagk' => 'TSAGK',
            'value' => 'No JSON value set',
            );
}
$encoded = json_encode($response);
header('Content-type: application/json');
exit($encoded);
?>

我的 android 中也有以下 APIService:

接口 APIService {

@POST("json.php")
@Headers("Content-Type: application/json;charset=utf-8", "Accept: application/json;charset=utf-8", "Cache-Control: max-age=640000")
fun savePost(
        @Body jsonObject: JSONObject
): Observable<Post>
}

在 MainActivity 我有 sendPost :

fun sendPost(user: String, pwd: String) {
    writeOnDebugger("sendPost()")
    val jsonObject = JSONObject()
    jsonObject.put("username", user)
    jsonObject.put("pass",pwd)
    jsonObject.put("latitude",35.5)
    jsonObject.put("longitude",36.5)

    writeOnDebugger(jsonObject.toString())

    // RxJava

    mAPIService?.savePost(jsonObject)?.subscribeOn(Schedulers.io())?.observeOn(AndroidSchedulers.mainThread())
            ?.subscribe(object : Subscriber<Post>() {
                override fun onCompleted() {
                    writeOnDebugger("onCompleted()")
                }

                override fun onError(e: Throwable) {
                    writeOnDebugger("onError()")
                }

                override fun onNext(post: Post) {
                    writeOnDebugger("onNext()")
                    showResponse(post.toString())
                }
            })
}

fun showResponse(response: String) {
    writeOnDebugger("showResponse()")
    if (mResponseTv?.getVisibility() === View.GONE) {
        mResponseTv?.setVisibility(View.VISIBLE)
    }
    mResponseTv?.setText(response)
}

我有一个帖子类:

class Post {

@SerializedName("username")
@Expose
var username: String? = null
@SerializedName("pass")
@Expose
var pass: String? = null
@SerializedName("latitude")
@Expose
var latitude: Double? = null
@SerializedName("longitude")
@Expose
var longitude: Double? = null
@SerializedName("id")
@Expose
var id: Int? = null

override fun toString(): String {
    return "Post{" +
            "username='" + username + '\''.toString() +
            ", pass='" + pass + '\''.toString() +
            ", latitude=" + latitude +
            ", longitude=" + longitude +
            ", id=" + id +
            '}'.toString()
}
}

改造客户端:

object RetrofitClient {

private var retrofit: Retrofit? = null
//    var gson = GsonBuilder()
//            .setLenient()
//            .create()
fun getClient(baseUrl: String): Retrofit? {
    if (retrofit == null) {
        retrofit = Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(/*gson*/))
                .build()
    }
    return retrofit
}
}

标签: phpandroidjsonkotlinrx-java

解决方案


目前,(在您的 php 文件中)您正在检查是否有任何带有 key== 的字段json。但是如果你仔细观察你的sendPost()函数,你永远不会json在正文中添加一个字段,因此响应不会是预期的。

解决方案可能是

val jsonObject = JSONObject()
jsonObject.put("type", type)
jsonObject.put("tsagk",tsagk)

val body = JSONObject()
body.put("json", jsonObject)

然后将body值传递给您的发布请求。


推荐阅读