2

I have a HttpServletResponse. I'd like to get the content of its entity, change it and then send the response.

Getting the content and changing it is simple : response.getEntity().getContent()

But writing back the modifications into the entity, ... I don't see how I can do it.

Do you have any suggestions?

yo_haha
  • 359
  • 1
  • 4
  • 15
  • @yo_hahaDid you solve your issue? – erhun Feb 13 '15 at 09:22
  • nop. I thought I could get content from entity to get the server response ... But it's not the case. I'm stuck at how to get the XML (that is the reponse I want) from the httpServletResponse – yo_haha Feb 13 '15 at 10:33

1 Answers1

1

You can write with a below way, responseFormat can be xml,json or other format. Read the responseOutput as byte array and then create header then set content type, set content length and write to httpEntity byte array.

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 is used.

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

erhun
  • 3,549
  • 2
  • 35
  • 44