我试图写一个InputStream
,这是我从一个获取URL
用doGet
方法Servlet
。 这里是我的代码:
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) {
}
}
}
}
}
我可以在控制台中看到responseCode
是200,但它不是写在页面什么。 在Firefox中我得到:
图像“the_context_root /水坝/无图像感知小服务程序?URL = HTTP%3A //本地主机%3A80 /文件/ MHIS044662和移交逃犯= 164FixedWidth&noSaveAs = 1”无法显示,因为它包含错误。
我无法找到我在做什么错。 任何指针将是非常有益的。