首页 > 解决方案 > Android Studio Volley - 无法访问 API

问题描述

初学者警报。

我正在尝试在 Android Studio 中使用 Volley 来访问我编写并托管在付费网络域上的 API。我在下面粘贴了我正在使用的代码。

该代码应该向 API 传递两个参数。第一个参数命名为“apicall”,第二个参数(从 mysql 数据库查询)命名为“q”。然而,总是返回错误响应消息(日志显示“pppp3:out”)。

我可以使用 Javascript 从网页访问此 API。所以我只是想知道下面的代码中是否缺少任何东西?


        String num1 = "selectjson";
        String num2 = "Select Region_Name from regions";

        String url = String.format("https://xxxxxxxxx.co.za/api/query_database_api.php?apicall=%1$s&q=%2$s", num1, num2);

        Log.d(TAG, "pppp1: " + url);

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        //atvAnimalName.setText("Response: " + response.toString());
                        Log.d(TAG, "pppp2: " + "In");
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d(TAG, "pppp3: " + "out");
                    }
                });

// Access the RequestQueue through your singleton class.
        ClsMySingleton.getInstance(actAddSighting.this).addToRequestQueue(jsonObjectRequest);

标签: androidandroid-volley

解决方案


如果您赢得使用日志调试 volley,请将您的 onErrorResponse 更改为

@Override
public void onErrorResponse(VolleyError error) {
       VolleyLog.d(TAG, "Error: " + error.getMessage());
}

之后你可以告诉我错误,我会尝试检查错误

编辑:因为您的错误日志是:

com.android.volley.ParseError: org.json.JSONException: Value [{"Region_Name":"Southern Africa"}] of type org.json.JSONArray cannot be converted to JSONObject

这意味着您的服务器响应是数组,您可以将您的请求更改为:

JsonArrayRequest jsonObjectRequest = new JsonArrayRequest
        (Request.Method.GET, url, null, new Response.Listener<JSONArray>() {

            @Override
            public void onResponse(JSONArray response) {
                //atvAnimalName.setText("Response: " + response.toString());
                Log.d(TAG, "pppp2: " + response.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
            }
        });

希望这有帮助


推荐阅读