下载指定url的图片

public static void getImg(String urlPath , String savePath) throws Exception {//获取图片
        
        URL url = new URL(urlPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(6*1000);  // 注意要设置超时,设置时间不要超过10秒,避免被android系统回收
        if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
        InputStream inSream = conn.getInputStream();
        //把图片保存到项目的根目录
        readAsFile(inSream, new File(savePath)); 
        
        
    }
	  public static void readAsFile(InputStream inSream, File file) throws Exception{//is 到 file转换
	        FileOutputStream outStream = new FileOutputStream(file);
	        byte[] buffer = new byte[1024];
	        int len = -1;
	        while( (len = inSream.read(buffer)) != -1 ){
	            outStream.write(buffer, 0, len);
	        }
	         outStream.close();
	        inSream.close();
	    }


                            

你可能感兴趣的:(url)