且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ANDROID& PHP-如何使用PHP从MySql显示JSONArray

更新时间:2023-01-20 16:30:50

问题

HttpURLConnection不支持JavaScript,但是使用JavaScript会生成所需的cookie.

HttpURLConnection has no JavaScript support, but a needed cookie is generated using JavaScript.

您的电话

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

失败,因为缺少__test cookie.

fails, because the cookie __test is missing.

修复

乍一看JavaScript来源,对于给定的URL cookie似乎是恒定的,因此为恒定cookie 设置足够了:

From a first glance at the JavaScript source the cookie seems to be constant for a given url, so it might be enough to set for a constant 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更改并且它没有太多时间延迟,它也不会破坏:>

Alternative: Using a WebView we can grab the cookie, so this is the preferable approach, since it will not break, if the cookie changes and it is not much of a time delay:

@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");
}

并按照上面的示例进行设置:

and set it as in above example:

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"}]