我如何从URL抓取图像,然后显示它...就像代理一样?
我认为我需要首先将图像传输到文件流然后输出文件。这是代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// temporarily hard-code the image
String imageUrlString = "http://i.imgur.com/3lQAD2E.jpg";
// Read the image ...
URL urlConn = new URL(imageUrlString);
InputStream inputStream = urlConn.openStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte [] buffer = new byte[ 1024 ];
int n = 0;
while (-1 != (n = inputStream.read(buffer))) {
output.write(buffer, 0, n);
}
inputStream.close();
// Here's the content of the image...
byte [] data = output.toByteArray();
PrintWriter out = response.getWriter();
out.print(data);
}
但是,返回只是一个损坏的图像文件。
答案 0 :(得分:1)
您应该使用OutputStream from the response而不是Writer。作家处理角色数据。您也可以set the MIME type correctly获得回复。