从网络路径中获取图片,并下载到指定的位置
-
拿到对应图片的路径,获取输入流
- HttpURLConnection继承了URLConnection,URLConnection代表应用程序和 URL 之间的通信链接
- 两者区别:HttpURLConnection对URLConnection功能进行了扩展,提供了基于http协议的api方法,最显著的是,前者提供了获取错误输入流,响应码等方法,这是 URLConnection做不到的(以下演示)
/** * 通过Get方式发起请求 */ public static InputStream getContentByGET(String url){ InputStream is = null; try { HttpURLConnection connection = getURLConnection(url,"GET"); //HttpURLConnection.HTTP_OK = 200(int类型的响应码,200在java代码中表示正常) if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { is = connection.getInputStream(); } else { is = getContentByPOST(url); } } catch (IOException ioe) { ioe.printStackTrace(); } return is; } /** * 通过Post方式 */ public static InputStream getContentByPOST(String url) { InputStream is = null; try { HttpURLConnection connection = getURLConnection(url,"POST"); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { is = connection.getInputStream(); } } catch (IOException ioe) {} return is; } /*** * 获取HttpURLConnection连接 */ public static HttpURLConnection getURLConnection(String path, String method){ URL url = null; HttpURLConnection connection = null; try { url = new URL(path); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); //设置超时时间(单位:毫秒):10秒 connection.setConnectTimeout(300000); connection.setReadTimeout(300000); connection.setRequestMethod(method); connection.setRequestProperty("Accept-Charset", "utf-8"); connection.setRequestProperty("contentType", "utf-8"); } catch (IOException e) {} return connection; } /** * 通过Post方式 */ public static InputStream getContentByPOST(String path) { InputStream is = null; try { HttpURLConnection connection = getURLConnection(path,"POST"); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { is = connection.getInputStream(); } } catch (IOException ioe) {} return is; }
-
通过上面方法拿到了InputStream,现打算从输入流中获取字节流数组,再通过文件输出流写入
@Test public void demo() throws IOException { InputStream inputStream = OAuthUtil.getContentByGET("https://img2.baidu.com/it/u=1003272215,1878948666&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1670950800&t=bb001d39822a6c5652025a658e940162"); byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); // 获取自己数组 byte[] getData = bos.toByteArray(); String savePath = "E:/Picture";//指定保存位置 // 文件保存位置 File saveDir = new File(savePath); if (!saveDir.exists()) { saveDir.mkdirs(); } File file = new File(saveDir + "/图片.jpeg"); //通过文件输出流写入 FileOutputStream fos = new FileOutputStream(file); fos.write(getData); if (fos != null) { fos.close(); } if (inputStream != null) { inputStream.close(); } }