Android-Volley:为JsonArrayRequest设置HTTP标头

b10*_*101 5 android json http-headers android-volley

所以我已经看到了几个JsonObjectRequests的例子,其中添加了这个代码

        @Override
        public String getBodyContentType() {
            return "application/json";
        }
Run Code Online (Sandbox Code Playgroud)

有时候这个代码已被使用

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            return headers;
        }
Run Code Online (Sandbox Code Playgroud)

无论哪种方式,它总是与JsonObjectRequest结合使用.我真的不知道在@OverrideJsonArrayRequest中添加方法的位置.这就是我的JsonArrayRequest的样子

JsonArrayRequest localJReq = new JsonArrayRequest(localURL,
      new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response){
            try{
                for (int i=0; i < response.length(); i++)
                {
                    JSONObject jsonObject = response.getJSONObject(i);
                    String title = jsonObject.getString("Title");
                    data += "Beschreibung: "+title+"\n\n\n";
                }
                output.setText(data);
            }catch (JSONException e){
                e.printStackTrace();
            }

        }
    },
            new Response.ErrorListener(){
                @Override
                public void onErrorResponse(VolleyError error){
                    error.printStackTrace();
                    Toast.makeText(MainActivity.this, "No more Items Available",
                          Toast.LENGTH_LONG).show();
                }
    });
Run Code Online (Sandbox Code Playgroud)

我试图{}在最后一次收盘后添加它,)但这不起作用.我试过把它放在里面Response.Listener也没用.所以我有点困惑.

无论如何我认为我制作JsonArrayRequest真的很奇怪,但由于我的REST API接受HTML和JSON作为响应,因此Volley似乎得到了HTML响应而不是JSON.这让我在我的应用程序中没有任何项目.这不是那种奇怪吗?既然它是一个JsonRequest,那么请求不应该将内容类型设置为application/json吗?我希望通过将content-type设置为application/json,我将得到正确的响应类型.

Bha*_*esh 6

您可以在请求结束时调用这些方法;

    JsonArrayRequest localJReq = new JsonArrayRequest(localURL,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
           }) {//here before semicolon ; and use { }.
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            return super.getHeaders();
        }

        @Override
        public String getBodyContentType() {
            return super.getBodyContentType();
        }
    };
Run Code Online (Sandbox Code Playgroud)