【发布时间】:2019-05-29 18:02:10
【问题描述】:
我正在了解Volley,但我不知道为什么 GET 方法的响应是单个字符 -> [。
我正在使用这种方法来获取 JSON 响应:
public void getJsonMethod() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
// String url = "https://www.w3schools.com/js/myTutorials.txt";
String url = "http://www.google.com"; // with this url I am getting response
// Request a string response from the provided URL.
final StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
System.out.println("Response is: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("Response is not good" + error.getMessage());
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
当我使用this link 时,我确实收到了响应,但是当我尝试使用一些只包含 JSON 的链接时,like this one 我的响应是“[”。
我是这样从 Activity 调用这个方法的:
GetJsonClass getJson = new GetJsonClass(this);
getJson.getJsonMethod();
关于我在这里做错了什么有什么想法吗?
答案+代码
如果有人开始使用 Volley,也许这可以帮助他:
正如 David Lacroix 在他的回答中所说,我打电话给 stringRequest 而不是JsonArrayRequest。
应该是这样的:
public void getJsonMethod() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
String url = "your url";
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
System.out.println("this is response good" + response);
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("this is response bad" + error);
}
});
queue.add(jsonObjectRequest);
}
【问题讨论】:
标签: android android-volley http-get