在Android中使用PHP API时没有响应.(Android) (PHP) (Volley)


No response when using Volley in Android with a PHP API. (Android) (PHP) (Volley)

我试图创建一个PHP API为我的Android应用程序使用。我正试图使用Volley来处理我的HTTP请求。我在PHP脚本中返回一个JSON字符串,但Volley只接收到一个'status=ok'响应。

这是我的Android应用程序中使用Volley的部分。

            //Make json string request
            StringRequest strReq = new StringRequest(Request.Method.GET,
                    url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    txtDisplay.setText(response);
                    System.out.println(response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error){
                    System.out.println(error);
            }
            });

这是我的PHP脚本

<?php
require($_SERVER["DOCUMENT_ROOT"] . "/resources/connection.php");
header('Content-type: application/json');
$response["success"] = 1;
$response["message"] = "Hello World! Database connection has been established!";
die(json_encode($response));
?>

我不明白为什么我得到的唯一回应是'status=ok'。我假设它与HTTP响应头代码200 OK有关,但我不知道。我做错了什么?

尝试在请求中添加Content-Type标头

           StringRequest strReq = new StringRequest(Request.Method.GET,
                    url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    txtDisplay.setText(response);
                    System.out.println(response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error){
                    System.out.println(error);
            }
            }){
            /**
             * Passing some request headers
             * */
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json");                   
                return headers;
            }     
        };

API被托管在我机器的本地主机上。我使用的URL是localhost。但是,我没有意识到Android设备不能直接与机器的本地主机通信。如果你在Android设备上调用localhost,它会引用设备自己的localhost web服务器。

要解决这个问题,只需使用您的机器的IP地址和运行API的端口。Android设备和机器必须在同一网络中。如果你正在使用App Engine,你还需要配置App Engine使用IP地址,而不仅仅是localhost。