开发者社区> 问答> 正文

为什么使用HttpClient发送json总是返回400?

android手机端需要发送一个json格式的数据,返回的也是json数据。 现在问题出现在,我无论怎么写都返回400,Bad Request。 问题出在哪儿呢?且看代码,感觉该设置的都设置了。 Java代码 收藏代码

/** 
     * POST获取服务端数据,发送的是json格式的数据 
     * @param urlString 
     * @param json 需要发送的json数据 
     * @return 
     * @throws ClientProtocolException 
     * @throws IOException 
     */  
    public String getDataFromServerByPostForJson(String urlString,JSONObject json) throws ClientProtocolException, IOException{  
        String strResult = null;  
        HttpClient client = new DefaultHttpClient();  
  
        StringEntity entity = new StringEntity(json.toString());  
        entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"));//"application/octet-stream"  
        entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING,HTTP.UTF_8));  
          
        HttpPost post = new HttpPost(urlString);  
        post.setHeader("Accept", "application/json");  
        post.setHeader("Content-Type", "application/json");  
        post.setEntity(entity);  
  
        HttpResponse response = client.execute(post);  
  
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
            strResult = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);  
        }else{  
            post.abort();  
            strResult = "Error Response code "  
                    + response.getStatusLine().getStatusCode() + " :"  
                    + response.getStatusLine().toString();  
            Log.i("tag", strResult);  
            return null;  
        }  
        return strResult;  
    }

有碰到类似的朋友吗?

展开
收起
长安归故里. 2020-01-07 13:54:38 1648 0
2 条回答
写回答
取消 提交回答
  • 我也碰到了这个问题,请问楼主解决了吗?

    2020-08-11 14:04:57
    赞同 展开评论 打赏
  • 发送请求的参数与后台 处理程序 的要求不匹配。

    特别是用 spring mvc时,容易出现该问题。

    比如 @RequestMapping("/api/ddd") public @ResponseBody JsonResult doDummy(@RequestParam("tid')Long id) { ..... return result; }

    如果发送的url是 http://www.foo.com/api/ddd 没有参数,则400 发送请求 http://www.foo.com/api/ddd?id=2323 因为实际要求的参数是tid不是id,还是会出400错

    2020-01-07 13:54:52
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载