【问题标题】:HttpPost return a empty bodyHttpPost 返回一个空的正文
【发布时间】:2016-02-29 15:39:36
【问题描述】:

我有下面的代码,我的问题是 response.status 是 200(没问题),我的响应正文是空的,它应该返回一个 json 响应。可能是长度的问题吗?:`

    HttpPost post = new HttpPost("http://localhost:8080/rest/login");
    httpClient = HttpClients.createDefault();

    List<NameValuePair> formParams = new ArrayList<NameValuePair>();
    NameValuePair pair = new BasicNameValuePair("token",token);
    formParams.add(pair);
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams);
    post.setEntity(entity);


    HttpResponse response = httpClient.execute(post);
    this.code = response.getStatusLine().getStatusCode();
    InputStream body = response.getEntity().getContent();
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));`

【问题讨论】:

  • token有效,有postman就可以了。
  • 在本地 REST 服务中添加一些断点或控制台输出,然后查看 POST 操作中的输入。并查看通过响应向客户提供的内容。我还会检查您的 MimeType 以获取响应。我猜它应该是“application/json”。
  • 我的 Post 调用返回 Json 格式的令牌,但我不知道是什么问题。使用 Postman(Chrome 工具),我可以毫无问题地使用这个 json 设置正文。

标签: java http-post httpclient


【解决方案1】:

我有类似的问题。就我而言,这也很奇怪,当 url 包含 IP 而不是主机名时,它起作用了(我得到了非空响应)。

但是,设置 netscape cookie 规范对我来说很有帮助。

httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom()
            .setCookieSpec(CookieSpecs.NETSCAPE)
            .build());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-25
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多