1
我正在嘗試編寫InputStream
,我從URL
獲得的doGet
方法。這裏是我的代碼:從URL中讀取InputStream並寫入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中我得到:
圖像0「the_context_root /水壩/無圖像感知,服務器URL = HTTP%3A //本地主機%3A80 /文件/ MHIS044662 &移交逃犯= 164FixedWidth & noSaveAs = 1 「 無法顯示,因爲它包含錯誤。
我無法找到我做錯了什麼。任何指針都會非常有幫助。
您可以在httpConnection.connect()之前使用響應代碼嗎? – Taylor
@泰勒我不知道我抓到你。你是否想在httpConnection.getResponseCode();之前調用'httpConnection.connect()'? –
是的。如果您在連接之前有響應代碼,我會很驚訝。 – Taylor