ITeye博客

通过内网中间服务器获取URL文件(图片)

leign · 2009-12-18 09:31 · JAVA · 编程语言 · Markdown

最近遇到这样一个问题: 服务器A不能上外网,但功能需求让它能获取URL的图片,于是想到用同域的另外一台能上外网的服务器B上进行中转。方法是,在服务器B其上写个JSP或Servlet,A通过访问B上的JSP或Servlet,B以流的形式吐出,A获取流数据并生成图片。

以下是主要的实现代码

A上的请求Action主要代码

try {
	String fileurl="http://www.iteye.com/upload/logo/user/166347/a62f68ef-ba87-3080-92ee-f95b3ff6189f.jpg?1257847065";	//图片外网地址
//	String midUrl = "http://B's_ip:port/service/getImageFromUrl.jsp" + "?url=" + 

fileurl;
	String midUrl = "http://192.168.106.28:8092/getImage.do" + "?url=" + fileurl;
						
	HttpURLConnection httpUrlCon = (HttpURLConnection)new URL(midUrl).openConnection();
	httpUrlCon.setDoOutput(true);
	httpUrlCon.setDoInput(true);
	httpUrlCon.connect();						
						
	InputStream inputs = httpUrlCon.getInputStream();
	BufferedImage image = ImageIO.read(inputs);
	
	File tmpFile = new File("temp\\tmpFile"+new Date());
	if(image!=null){
		ImageIO.write(image, "jpg", tmpFile);
	}
} catch (IOException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	}
}

B上的服务Serlvet类

public class GetImageServlet extends HttpServlet{
	public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
		String url = request.getParameter("url");
		System.out.println("url===="+url);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		
		String filePath = "\tmpPath\\tmpFile"+sdf.format(new Date())+".jpg";

		System.out.println("filePath===="+filePath);
		try{
			File tmpFile = new File(filePath);
			FileUtils.copyURLToFile(new URL(url), tmpFile);
			
			ServletOutputStream souts = response.getOutputStream();
			response.setContentType("image/jpeg");

			BufferedImage image = ImageIO.read(tmpFile);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(souts);
			JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
			encoder.encode(image, param);
			
			ImageIO.write(image,"jpeg",response.getOutputStream());

			souts.close();

		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
		this.doGet(request, response);
	}
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。