gpt4 book ai didi

php - 从 Android 接收 PHP 脚本中的 JSON 对象

转载 作者:太空狗 更新时间:2023-10-29 14:10:13 25 4
gpt4 key购买 nike

这是我第一次使用 JSON 开发 PHP 站点,并且还使用 Android 设备上的在线数据库,我的问题是我不知道为什么我的脚本返回 null,我还没有' 向它发送任何变量。

我的 PHP 代码是:

<?php

$data = file_get_contents('php://input');
$json = json_decode($data, true);

var_dump($json);

?>

问题是:收集 Android 设备发送到我的 php 的 JSON 数据的方式是什么?

如果有人问这是我将数据从我的 Android 设备发送到 php 的方式:

在我的 android 应用程序中,我以这种方式发送 JSON 对象:

    HttpResponse response =null;
DefaultHttpClient httpClient = new DefaultHttpClient();

HttpConnectionParams.setSoTimeout(httpClient.getParams(), 5000);
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),3000);

HttpPost request = new HttpPost(url);

StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
try{
response = httpClient.execute(request);
}catch(SocketException sE)
{
throw sE;
}

我从我的 android 代码发送的数据结构如下:

JSONObject json = new JSONObject();
try {
json.put("user", 0);
json.put("status", "Confirmed");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

最佳答案

感谢 Mike Miller 的评论,我找到了问题的解决方案.

问题不在 PHP 中,而是在 android 应用程序中,因为我没有从 Android 设备发送任何内容。

所以正确的解决方案是:

    HttpResponse response =null;
DefaultHttpClient httpClient = new DefaultHttpClient();

HttpConnectionParams.setSoTimeout(httpClient.getParams(), 5000);
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),3000);

HttpPost request = new HttpPost(url);

//Adding a header for the string
request.setHeader("json", json.toString());

StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));

//adding the StringEntitu to the request
request.setEntity(se);

try{
response = httpClient.execute(request);
}
catch(SocketException sE)
{
Log.e("SocketException", sE+"");
throw sE;
}

非常感谢所有帮助过我的人!

关于php - 从 Android 接收 PHP 脚本中的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29611745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com