【问题标题】:Volley Post method gives me unexpected response code 400?Volley Post 方法给了我意外的响应代码 400?
【发布时间】:2016-02-17 12:25:05
【问题描述】:

这是一个新的 android 开发我正在尝试使用 gson lib 将 json 值发布到服务器,我已转换为 json,但是当我尝试发送到服务器时抛出 400 意外响应代码,让我发布我的代码:

listobj = account_sf_db.toServer();
    Gson gson = new Gson();
    RequestQueue queue = Volley.newRequestQueue(getBaseContext());
 final String yog = gson.toJson(listobj);

    String URL = "http://xxx.xx.xx.xxx/xxx/CRM/AcoountCreatePageLoad.svc/xxt/xxxt/ " +yog ;




            StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            String resp = response.toString();
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {


                }
            })

    {

        @Override
        protected Map<String, String> getParams() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("god", yog);


        return params;
    }  @Override
       public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Content-Type", "application/json");
                    headers.put("Accept","application/json");
                    headers.put("User-agent", "My useragent");
                    return headers;
                }

    };
         queue.add(stringRequest);
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

}

【问题讨论】:

    标签: android json android-volley


    【解决方案1】:

    400 状态码用于Bad Request,表示服务器不期待此类请求。

    由于语法错误,服务器无法理解请求。客户端不应该在没有修改的情况下重复请求。

    请检查您添加的标头(内容类型、用户代理等)是否需要。服务器可能会期待一个简单的请求,而不是 json 请求。

    同时尝试读出您在onErrorResponse 中遇到的错误。服务器可能已经响应了您预期的参数和请求类型,并且还讨论了 Web 开发人员开发的 API 类型。

    【讨论】:

    • 您的服务器期望什么参数?我看到您将 JSON 数据作为参数 god 发布。 god 是正确的参数名称,还是这可能是您得到 400 - Bad request 的原因?
    • @Yog 我们不能期待完美的答案,甚至服务器(Web 开发)也可以手动抛出异常,就像我们可以在 Andorid/Java 中抛出异常一样。所以最好和 Web 开发人员讨论请求类型、标头和参数。也将 errorResponse 的响应发送给 dev。
    【解决方案2】:

    您的网址中 /xxt/xxxt/ 后面有一个空格

    字符串 URL = "http://xxx.xx.xx.xxx/xxx/CRM/AcoountCreatePageLoad.svc/xxt/xxxt/ " +yog ;

    删除它,我想你会没事的。

    P.S 400 一般表示 Url 或参数有问题。

    【讨论】:

      猜你喜欢
      • 2019-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多