【问题标题】:Why Volley response is received as "[" and not JSON为什么 Volley 响应被接收为“[”而不是 JSON
【发布时间】: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


    【解决方案1】:

    https://developer.android.com/training/volley/request

    字符串请求。指定一个 URL 并接收一个原始字符串作为响应。有关示例,请参阅设置请求队列。 JsonObjectRequest 和 JsonArrayRequest(JsonRequest 的两个子类)。指定一个 URL 并获取一个 JSON 对象或数组(分别)作为响应。

    您应该使用JsonArrayRequest

    【讨论】:

      【解决方案2】:

      myTutorials.txt 的状态码为 304(也没有正确的后缀和 MIME 类型):

      304 未修改。如果客户端已经执行了一个条件 GET 请求并且允许访问,但是文档没有被修改,服务器应该用这个状态码来响应。 304 响应不得包含消息正文,因此始终以标头字段后的第一个空行终止。

      换句话说,浏览器可能显示的内容不一定与服务器发送的内容相同。例如。 GSON 将接受 JSON 仅启用选项 lenient,因为数组没有名称。

      RFC 2616

      【讨论】:

      • 嘿@Martin Zeitler,感谢您花时间回答这个问题。检查接受的答案,看看我的问题是什么。尽管如此,这可能不适用于您的答案包含有用信息的问题 - 您得到了我的支持。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-29
      相关资源
      最近更新 更多