POST 与 headers 和 body 的 Volley 请求(java、android 工作室)

POST request with Volley with headers and body (java, android studio)

我正在尝试在 Android Studio 中使用 Volley 发送 POST 请求。但是,我想设置一些 headers 和一个 body。我怎样才能做到这一点? 在这种情况下,headersidkey。我应该在哪里添加 body?我试图了解 Whosebug 中关于这些问题的大量问题。但是,headers 和 body 似乎仍未正确发送。

        try {
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            String URL = "https://url.of.the.server";
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("Content-Type", "application/json");
            jsonBody.put("id", "oneapp.app.com");
            jsonBody.put("key", "fgs7902nskagdjs");
            final String requestBody = jsonBody.toString();

            StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.i("VOLLEY", response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("VOLLEY", error.toString());
                }
            }) {
                @Override
                public String getBodyContentType() {
                    return "application/json; charset=utf-8";
                }

                @Override
                public byte[] getBody() throws AuthFailureError {
                    try {
                        return requestBody == null ? null : requestBody.getBytes("utf-8");
                    } catch (UnsupportedEncodingException uee) {
                        VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                        return null;
                    }
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String>  params = new HashMap<String, String>();
                    params.put("Content-Type", "application/json");
                    params.put("id", "oneapp.app.com");
                    params.put("key", "fgs7902nskagdjs");

                    return params;
                }

                @Override
                protected Response<String> parseNetworkResponse(NetworkResponse response) {
                    String responseString = "";
                    if (response != null) {
                        responseString = String.valueOf(response.statusCode);
                        // can get more details such as response.headers
                    }
                    return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
                }
            };
            Log.d("string", stringRequest.toString());
            requestQueue.add(stringRequest);
        } catch (JSONException e) {
            e.printStackTrace();
        }

非常感谢您的帮助。

您设置正确 headers,您可以试试这个

 try {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String URL = "https://url.of.the.server";

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("VOLLEY", response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("VOLLEY", error.toString());
            }
        }) {
            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                try {
                     // request body goes here
                     JSONObject jsonBody = new JSONObject();
                     jsonBody.put("attribute1", "value1");
                     String requestBody = jsonBody.toString();
                    return requestBody.getBytes("utf-8");
                } catch (UnsupportedEncodingException uee) {
                    VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                    return null;
                }
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String>  params = new HashMap<String, String>();
                params.put("Content-Type", "application/json");
                params.put("id", "oneapp.app.com");
                params.put("key", "fgs7902nskagdjs");

                return params;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String responseString = "";
                if (response != null) {
                    responseString = String.valueOf(response.statusCode);
                    // can get more details such as response.headers
                }
                return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        Log.d("string", stringRequest.toString());
        requestQueue.add(stringRequest);
    } catch (JSONException e) {
        e.printStackTrace();
    }

例如,如果请求 body 是

{
  name: "name1",
  email: "email1"
}

getBody 方法将是

@Override
public byte[] getBody() throws AuthFailureError {
 JSONObject jsonBody = new JSONObject();
 jsonBody.put("name", "name1");
 jsonBody.put("email", "email1");
 String requestBody = jsonBody.toString();
 return requestBody.getBytes("utf-8");
}