java的get请求获取网络中的图片
写项目的时候写的,感觉以后还会用,所以记录一下
一种通过 java 的get请求获取 网上图片的数据 二种,通过获取本地的具体文件下的图片的数据
前台写的
date.t.avatat 是 存在数据库中 图片的地址 一种是本地地址 一种是 http地址
后台
@RequestMapping("getImagesByAll") @ResponseBody public void getImagesByAll(HttpServletResponse response, String picture){ //设置返回的数据类型 response.setContentType("image/jpeg;charset=utf-8"); ServletOutputStream outputStream = null; try { outputStream = response.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } //不是 ./images/xxx.jpg if(!picture.startsWith("./")){ //通过java实现http的get请求 try{ URL url = new URL(picture); HttpURLConnection urlCon= (HttpURLConnection)url.openConnection(); if(200==urlCon.getResponseCode()){ InputStream is = urlCon.getInputStream(); byte[] buffer = new byte[1024]; int len =0; while(( len = is.read(buffer)) >0 ){ outputStream.write(buffer,0,len); } outputStream.close(); is.close(); } }catch(Exception e){ e.printStackTrace(); } }else{ //本地服务器中的图片 //是 ./images/xxx.jpg D:ideaMyBlogsrcmain esourcesstaticimagesavatar.jpg String pictureName = picture.split("/")[2]; //打印一下 xxx.jpg System.out.println(picture); String pictureAddress = "D:\idea\MyBlog\src\main\resources\static\images\"+pictureName; //打印一下 D:ideaMyBlogsrcmain esourcesstaticimagesavatar.jpg System.out.println(pictureAddress); try { FileInputStream fis = new FileInputStream(pictureAddress); byte[] buffer = new byte[1024]; int len = 0 ; //将图片数据想要到浏览器 while( (len = fis.read(buffer)) > 0 ){ outputStream.write(buffer,0,len); } fis.close(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } }
上一篇:
Java架构师技术进阶路线图
下一篇:
TCP的三次握手、四次挥手