php - 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
}
}
解决方案
目前,(在您的 php 文件中)您正在检查是否有任何带有 key== 的字段json
。但是如果你仔细观察你的sendPost()
函数,你永远不会json
在正文中添加一个字段,因此响应不会是预期的。
解决方案可能是
val jsonObject = JSONObject()
jsonObject.put("type", type)
jsonObject.put("tsagk",tsagk)
val body = JSONObject()
body.put("json", jsonObject)
然后将body
值传递给您的发布请求。
推荐阅读
- kubernetes - CoreDNS 将所有 DNS 查询转发到本地路由器,包括集群内服务名称的查询
- javascript - Swiper.js 分页自定义项目符号不会点击移动到下一张幻灯片
- linux - 使用 signal_pending_state 函数将任务状态更改为 TASK_RUNNING
- azure-sql-database - Web 应用程序和 SQL Server 之间的白名单 IP
- javascript - 如何使用 discord.js 获取 URL 的信息
- java - Eclipse MAT OQL 某个包中的类列表
- javascript - 以角度显示从 ngx-data-table 中选择的用户详细信息
- html - 将文本放在 div 的中心,同时忽略其中的其他元素
- python - 将实例列表放入数据框中,但一个属性是另一个字典列表
- python - 无论我做什么,超级简单的 Flask 应用程序的云构建都失败了