【问题标题】:How to update HttpEntity content?如何更新 HttpEntity 内容?
【发布时间】:2015-04-13 11:48:08
【问题描述】:

我有一个 HttpServletResponse。我想获取其实体的内容,对其进行更改,然后发送响应。

获取内容和更改内容很简单:response.getEntity().getContent()

但是将修改写回实体中,...我不知道该怎么做。

你有什么建议吗?

【问题讨论】:

  • @yo_haha你的问题解决了吗?
  • 没有。我以为我可以从实体获取内容以获取服务器响应……但事实并非如此。我被困在如何从 httpServletResponse 获取 XML(这是我想要的响应)

标签: servlets httpentity


【解决方案1】:

您可以使用以下方式编写,responseFormat 可以是xml,json 或其他格式。将responseOutput读取为byte数组,然后创建header,然后设置内容类型,设置内容长度并写入httpEntity字节数组。

public HttpEntity<byte[]> writeResponse(String responseOutput, String responseFormat) {
        byte[] documentBody = null;
        try {
            documentBody = responseOutput.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        HttpHeaders header = new HttpHeaders();
        header.setContentType(new MediaType("application", responseFormat));//response format can be "json"
        header.setContentLength(documentBody.length);
        return new HttpEntity<byte[]>(documentBody, header);
    }

*EDIT : * 使用了 org.springframework.http.HttpEntity。

Apache org.apache.http.HttpEntity example

public String execute() throws ClientProtocolException, IOException {
  if (response == null) {
    HttpClient httpClient=HttpClientSingleton.getInstance();
    HttpResponse serverresponse=null;
    serverresponse=httpClient.execute(httppost);
    HttpEntity entity=serverresponse.getEntity();
    StringWriter writer=new StringWriter();
    IOUtils.copy(entity.getContent(),writer);
    response=writer.toString();
  }
  return response;
}

IOUtils.copy

【讨论】:

  • 您从哪个包中使用了 HttpEntity? org.apache.http.HttpEntity 中的那个不是通用的。
  • IOUtils.copy 不接受 StringWriter 作为参数
  • @yo_haha 检查你的版本,应该是 org.apache.commons.io.IOUtils 2.4 我更新我的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 2016-11-01
  • 2020-09-23
  • 2021-03-11
  • 2012-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多