【问题标题】:POST request with Volley with headers and body (java, android studio)带有标头和正文的 Volley POST 请求(java,android studio)
【发布时间】:2021-08-11 07:15:12
【问题描述】:

我正在尝试在 Android Studio 中使用 Volley 发送 POST 请求。但是,我想设置一些标题和正文。我怎样才能做到这一点? 在这种情况下,headers 是 id 和 key。我应该在哪里添加正文?我试图关注 StackOverflow 中关于这些问题的众多问题。但是,标题和正文似乎仍然没有正确发送。

        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();
        }

非常感谢您的帮助。

【问题讨论】:

  • 您好,您收到的请求响应是什么?
  • 这是回复:2021-05-22 13:17:00.614 22209-22982/com.example.chattutorial E/Volley: [43149] BasicNetwork.performRequest: Unexpected response code 400 for https://url.of.the.server 2021-05-22 13:17:00.617 22209-22209/com.example.chattutorial E/VOLLEY: com.android.volley.ClientError 2021-05-22 13:17:00.666 22209-22994/com.example.chattutorial E/Volley: [43156] BasicNetwork.performRequest: Unexpected response code 400 for https://url.of.the.server 2021-05-22 13:17:00.667 22209-22209/com.example.chattutorial E/VOLLEY: com.android.volley.ClientError
  • @Vinujan.S 你认为标题在正确的位置吗?
  • 您似乎收到 400 错误代码。这意味着您的标题和正文是错误的。您可以通过启用 volley 的调试日志来了解更多信息。通过调试日志,您可以观察到实际的请求结构,然后您可以与实际请求进行比较并找到问题。
  • 通过查看您的代码,您发送的正文和标题相同。是什么原因?

标签: java android-studio http-post android-volley


【解决方案1】:

你正确设置了标题,你可以试试这个

 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();
    }

例如,如果请求正文是

{
  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");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-13
    • 2020-01-02
    • 2017-08-31
    • 2021-05-24
    • 2016-09-24
    • 2020-12-23
    • 1970-01-01
    • 2015-11-28
    相关资源
    最近更新 更多