0

我看过很多博客和链接,但找不到满意的答案。我在我的应用程序中使用 volley 发出一个简单的POST请求(JSONObjectRequest) ,但在 volley 错误中得到com.android.volley.ServerError 。我使用的 URL 是“ http://192.XXX.X.XX:8080/zin-pushnotification_stage/pushnotification/service/register ”。凌空是否有可能不支持其中包含端口号的网址?需要一个简单而精确的解决方案。

代码:

Map<String, String> body = new HashMap<>();
body.put("deviceId", "STECH-1502878253");
body.put("token", "XYZ");
body.put("deviceType", "IPHONE");
body.put("companyKey", "STECH");
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,"http://192.XXX.X.XX:8080/zin-pushnotification_stage/pushnotification/service/register", new JSONObject(body), new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.e("Data response", response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("VolleyError","Error response", error);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> header = new HashMap<>();
                header.put("Content-Type", ApplicationConstants.Content_Type);
                header.put("Authorization", ApplicationConstants.CUSTOM_AUTH_TOKEN);
                return header;
            }
        };

        requestQueue.add(request);

堆栈跟踪:

E/Volley: [35860] BasicNetwork.performRequest: Unexpected response code 400 for http://192.XXX.X.XX:8080/zin-pushnotification_stage/pushnotification/service/register
W/System.err: com.android.volley.ServerError
W/System.err:     at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:163)
W/System.err:     at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)
4

1 回答 1

1

JsonObjectRequest延伸JsonRequest。如果你看一下JsonRequest你会发现的源代码:

 /** Default charset for JSON request. */
protected static final String PROTOCOL_CHARSET = "utf-8";

/** Content type for request. */
private static final String PROTOCOL_CONTENT_TYPE =
String.format("application/json; charset=%s", PROTOCOL_CHARSET);

@Override
    public String getBodyContentType() {
        return PROTOCOL_CONTENT_TYPE;
}

所以默认情况下JsonObjectRequest将标题设置为. 您所做的是还发送另一个导致服务器响应 status 的标头。通过删除该行来删除额外的标题:content-typeapplication/json; charset=utf-8content-type400

header.put("Content-Type", ApplicationConstants.Content_Type);

请求仅包含正确的默认标头。

于 2017-11-01T14:22:05.347 回答