我用来将表的值显示到下面的 JSONArray 中的代码
send_data.php
<?php
include 'dbconfig.php';
$con = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "select id,ask from pertanyaan";
$result = mysqli_query($con,$query);
$rows = array();
while($r = mysqli_fetch_array($result)) {
$rows[] =$r;
}
echo json_encode(array_values($rows));
mysqli_close($con);
?>
JSONArray 输出类似于 this
[{"0":"1","id":"1","1":"pertanyaan ke 1","ask":"pertanyaan ke 1"},{"0":"2","id":"2","1":"pertanyaan ke 2","ask":"pertanyaan ke 2"},{"0":"3","id":"3","1":"pertanyaan ke 3","ask":"pertanyaan ke 3"},{"0":"4","id":"4","1":"pertanyaan ke 4","ask":"pertanyaan ke 4"},{"0":"5","id":"5","1":"pertanyaan ke 5","ask":"pertanyaan ke 5"}]
但是每次我尝试在 Android 中显示该 URL 时,都会收到一条错误消息
Value <html><body<>script of type java.lang.String cannot be converted to JSONArray
但是当我创建具有相同输出的新 API 时 here进入android studio,它工作正常,
我是否使用了错误的代码从 PHP 编码 JSON?
最佳答案
问题
HttpURLConnection
不支持 JavaScript,但需要的 cookie 是使用 JavaScript 生成的。
您的来电
String reqUrl = "http://zxccvvv.cuccfree.com/send_data.php";
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
失败,因为 cookie __test
丢失。
修复
乍一看 JavaScript 源代码,cookie 对于给定的 url 似乎是恒定的,因此设置常量 cookie 可能就足够了:
String cookie = "__test=2bf7c15501c0ec57f8e41cb84871a69c";
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(7000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Cookie", cookie);
替代方案:使用 WebView 我们可以获取 cookie,因此这是更好的方法,因为如果 cookie 发生变化并且没有太多时间延迟,它不会中断:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getCookie();
if(cookie!=null) {
new GetContacts().execute();
}
}
private void getCookie(){
CookieManager.setAcceptFileSchemeCookies(true);
WebView wv = new WebView(getApplicationContext());
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl(url);
cookie = CookieManager.getInstance().getCookie("zxccvvv.cuccfree.com");
}
并按照上面的示例进行设置:
conn.setRequestProperty("Cookie", cookie);
logcat 中的输出
Response from url: [{"0":"1","id":"1","1":"pertanyaan ke 1","ask":"pertanyaan ke 1"},{"0":"2","id":"2","1":"pertanyaan ke 2","ask":"pertanyaan ke 2"},{"0":"3","id":"3","1":"pertanyaan ke 3","ask":"pertanyaan ke 3"},{"0":"4","id":"4","1":"pertanyaan ke 4","ask":"pertanyaan ke 4"},{"0":"5","id":"5","1":"pertanyaan ke 5","ask":"pertanyaan ke 5"}]
关于php - ANDROID&PHP - 如何使用 PHP 从 MySql 显示 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40199853/