android - 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);
解决方案
如果您赢得使用日志调试 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());
}
});
希望这有帮助
推荐阅读
- json - 访问响应数组中的变量
- codenameone - 解析 json 数据时可以看到以前的选项卡组件 - cn1
- mongodb - 异常 - 无法在 java 类的 jasper 报告中获取数值字段值的值
- scala - Scala Future.find
- javascript - 如何访问 $.widget 选项值?
- python - Pyqt QTablewidget 自动换行
- java - 卡夫卡消费者收到相同的消息
- regex - 打开```后添加语言注释
- ssl-certificate - 从 vertx 的客户端证书中提取用户主体
- visual-studio - Visual Studio 2017 中的“显示片段突出显示”在哪里?