Java代码如何从网络中获取资源呢?
下文笔者讲述java代码从网络中获取资源的方法分享,如下所示
网络获取资源的实现思路: 1.定义一个URL对象 2.借助HttpURLConnection对象打开URL对象 3.使用getInputStream下载网络上的资源例:下载指定URL上的资源
InputStream in = null; byte[] data = null; URL url = new URL("你的url"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { //conn.getContentLength() 获取到读取的数据流大小 log.info("文件名={},文件长度={}",fileName,conn.getContentLength()); in = conn.getInputStream(); data = new byte[conn.getContentLength()]; int total = 0; int len = 0; //read(byte b[], int off, int len).b为缓冲区;off为读取字节的下标;len为每次读取的长度 while ((len = in.read(data, total, conn.getContentLength() - total > 1024 ? 1024 : conn.getContentLength() - total)) != -1) { total = total + len; } in.close(); conn.disconnect(); }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。