I am trying to write an InputStream
, which I get from an URL
by the doGet
method of Servlet
. Here is my code:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestedUrl = request.getParameter("url");
if (StringUtils.isNotBlank(requestedUrl)) {
ReadableByteChannel inputChannel = null;
WritableByteChannel outputChannel = null;
try {
URL url = new URL(requestedUrl);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
int responseCode = httpConnection.getResponseCode();
System.out.println(responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
response.setContentType("image/jpg");
httpConnection.connect();
InputStream imageStream = url.openStream();
OutputStream outputStream = response.getOutputStream();
inputChannel = Channels.newChannel(imageStream);
outputChannel = Channels.newChannel(outputStream);
ByteBuffer buffer = ByteBuffer.allocate(10240);
while (inputChannel.read(buffer) != -1) {
buffer.flip();
outputChannel.write(buffer);
buffer.clear();
}
}
} catch (Exception ex) {
Log.error(this, ex.getMessage(), ex);
} finally {
if (ObjectUtils.notEqual(outputChannel, null)) {
try {
outputChannel.close();
} catch (IOException ignore) {
}
}
if (ObjectUtils.notEqual(inputChannel, null)) {
try {
inputChannel.close();
} catch (IOException ignore) {
}
}
}
}
}
I can see in console that the responseCode
is 200 but it is not writing anything in the page. In Firefox I am getting:
The image “the_context_root/dam/no-image-aware-servlet?url=http%3A//localhost%3A80/file/MHIS044662&Rendition=164FixedWidth&noSaveAs=1” cannot be displayed because it contains errors.
I am unable to find what I am doing wrong. Any pointer would be very helpful.