定义一个读取输入流的工具类
package cn.mzba.utils; import java.io.ByteArrayOutputStream; import java.io.InputStream; public class StreamTool { /** * 读取输入流数据 * @param is * @return * @throws Exception */ public static byte[] readStream(InputStream is)throws Exception{ ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int len = 0; while((len = is.read(buffer)) != -1){ os.write(buffer,0,len); } is.close(); return os.toByteArray(); } }
?根据指定的路径获取网络上的内容
?
package cn.mzba.utils; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class ImageService { public static void main(String[] args) throws Exception{ String path = "http://images.enet.com.cn/2007/1024/46/1917978.jpg"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); if(conn.getResponseCode() == 200){ InputStream is = conn.getInputStream(); byte[] data = StreamTool.readStream(is); File file = new File("sex.jpg"); FileOutputStream fs = new FileOutputStream(file); fs.write(data); fs.close(); }else{ System.out.println("请求失败"); } } }?刷新项目,就会在根目录底下看到一个sex.jpg的图片了。