我有一个HttpServletResponse。我想得到它的实体的内容,更改它,然后发送响应。
获取内容并更改内容很简单:response.getEntity().getContent()
但把修改写回实体里.我不知道该怎么做。
你有什么意见建议?
发布于 2015-02-12 20:59:37
您可以用下面的方式编写,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);
}*编辑:*使用 org.springframework.http.HttpEntity。
Apache org.apache.http.HttpEntity 示例
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;
}https://stackoverflow.com/questions/28482604
复制相似问题