ANDROID和PHP – 如何使用PHP从MySql显示JSONArray

我用来在下面的JSONArray中显示表的值的代码

send_data.php

  

并且JSONArray输出是这样的

[{"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 <bodyscript of type java.lang.String cannot be converted to JSONArray

但是当我在 android studio中创建具有相同输出的新API时,它的工作正常,

我是否使用错误的代码从PHP编码JSON?

问题

HttpURLConnection没有JavaScript支持,但是使用JavaScript生成了所需的cookie。

你的来电

 String reqUrl = "http://zxccvvv.cuccfree.com/send_data.php"; URL url = new URL(reqUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 

失败,因为缺少cookie __test

固定

从第一眼看来,对于给定的URL,cookie似乎是常量,因此设置一个常量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"}]