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