• java 多线程下载文件 以及URLConnection和HttpURLConnection的区别


    使用 HttpURLConnection 实现多线程下载文件  注意GET大写
    //
    http public class MultiThreadDownload { public static void main(String[] args) { URL url = null; int fileLength = 0; try { url = new URL("http://www.baidu.com/img/baidu_sylogo1.gif"); //使用http协议 也可以直接用urlconnection 输入流处理不同 HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); fileLength = con.getContentLength(); System.out.println("fileLength: "+ fileLength); } catch (IOException e) { System.out.println("can not open url"); } File localFile = new File("d:/2.gif"); try { RandomAccessFile rf = new RandomAccessFile(localFile, "rw"); rf.setLength(fileLength); //写一个空文件 rf.close(); } catch (IOException e) { System.out.println("file not exists"); } int thread_num = 3; int start; int end; int blockSize = fileLength/thread_num==0?fileLength/thread_num:(fileLength/thread_num+1); for(int i=0; i<thread_num; i++){ start = i * blockSize; if(i != thread_num-1){ end = start + blockSize - 1; }else{ end = fileLength; } System.out.println(i+"="+start+","+end); new MyThreadDownload(localFile, url, start, end).start(); } } } class MyThreadDownload extends Thread{ private File file; private URL url; private int start; private int end; public MyThreadDownload(File file, URL url, int start, int end) { this.file = file; this.url = url; this.start = start; this.end = end; } public void run() { try { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); //大写 con.setRequestProperty("Range", "bytes="+start+"-"+end); if(con.getResponseCode() == 200){ InputStream is = con.getInputStream(); RandomAccessFile rf = new RandomAccessFile(file, "rwd");// rwd使用缓冲区 rf.seek(start);//跳到某一位置开始 byte[] buf = new byte[1024]; int len = 0; while((len = is.read(buf))!=-1){ rf.write(buf, 0, len); } rf.close(); is.close(); } } catch (Exception e) { e.printStackTrace(); } } }

    URLConnection与HttpURLConnection区别

    URLConnection与HttpURLConnection都是抽象类,无法直接实例化对象。其对象主要通过URL的openconnection方法获得。

    值得注意的是:
    1.openConnection方法只创建URLConnection或者HttPURLConnection实例,但是并不进行真正的连接操作。并且,每次openConnection都将创建一个新的实例。
    2.openConnection不进行的连接操作的原因在于,可以在连接操作进行之前,对URLConnection或者HttPURLConnection实例的某些属性进行设置,如设置超时值等。

    3.无论URLConnection或者HttPURLConnection实例,其getInputStream之类属于应用层的操作,都会调用connect操作。但是,connectTimeout与ReaderTimeout并不相同。有可能在已连接的情况下,仍然Reader超时

    利用HttpURLConnection对象和Internet交互 


    1.从Internet获取网页
    发送请求,将网页以流的形式读回来.
    1)创建一个URL对象:URL url = new URL("http://www.sohu.com");
    2)利用HttpURLConnection对象从网络中获取网页数据:HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    3)设置连接超时:conn.setConnectTimeout(6* 1000);
    4)对响应码进行判断:if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
    5)得到网络返回的输入流:InputStream is = conn.getInputStream();
    6)String result = readData(is, "GBK");
    conn.disconnect();
    总结:
    --我们必须要记得设置连接超时,如果网络不好,Android系统在超过默认时间会收回资源中断操作.
    --返回的响应码200,是成功.
    --利用ByteArrayOutputStream类,将得到的输入流写入内存.
    --在Android中对文件流的操作和JAVA SE上面是一样的.

    2.从Internet获取文件
    利用HttpURLConnection对象,我们可以从网络中获取文件数据.
    1)创建URL对象,并将文件路径传入:URL url = new URL("http://photocdn.sohu.com/20100125/Img269812337.jpg");
    2)创建HttpURLConnection对象,从网络中获取文件数据:HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    3)设置连接超时:conn.setConnectTimeout(6* 1000);
    4)对响应码进行判断:if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
    5)得到网络返回的输入流:InputStream is = conn.getInputStream();
    6)将得到的文件流写出:outStream.write(buffer, 0, len);
    总结:
    --在对大文件的操作时,要将文件写到SDCard上面,不要直接写到手机内存上.
    --操作大文件是,要一遍从网络上读,一遍要往SDCard上面写,减少手机内存的使用.这点很重要,面试经常会被问到.
    --对文件流操作完,要记得及时关闭.

    3.向Internet发送请求参数
    1)将地址和参数存到byte数组中:byte[] data = params.toString().getBytes();
    2)创建URL对象:URL realUrl = new URL(requestUrl);
    3)通过HttpURLConnection对象,向网络地址发送请求:HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
    4)设置容许输出:conn.setDoOutput(true);
    5)设置不使用缓存:conn.setUseCaches(false);
    6)设置使用POST的方式发送:conn.setRequestMethod("POST");            
    7)设置维持长连接:conn.setRequestProperty("Connection", "Keep-Alive");
    8)设置文件字符集:conn.setRequestProperty("Charset", "UTF-8");
    9)设置文件长度:conn.setRequestProperty("Content-Length", String.valueOf(data.length));
    10)设置文件类型:conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    11)以流的方式输出.
    总结:
    --发送POST请求必须设置允许输出
    --不要使用缓存,容易出现问题.
    --在开始用HttpURLConnection对象的setRequestProperty()设置,就是生成HTML文件头.

    4.向Internet发送xml数据
    XML格式是通信的标准语言,Android系统也可以通过发送XML文件传输数据.
    1)将生成的XML文件写入到byte数组中,并设置为UTF-8:byte[] xmlbyte = xml.toString().getBytes("UTF-8");
    2)创建URL对象,并指定地址和参数:URL url = new URL("http://localhost:8080/itcast/contanctmanage.do?method=readxml");
    3)获得链接:HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    4)设置连接超时:conn.setConnectTimeout(6* 1000);
    5)设置允许输出conn.setDoOutput(true);
    6)设置不使用缓存:conn.setUseCaches(false);
    7)设置以POST方式传输:conn.setRequestMethod("POST");            
    8)维持长连接:conn.setRequestProperty("Connection", "Keep-Alive");
    9)设置字符集:conn.setRequestProperty("Charset", "UTF-8");
    10)设置文件的总长度:conn.setRequestProperty("Content-Length", String.valueOf(xmlbyte.length));
    11)设置文件类型:conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
    12)以文件流的方式发送xml数据:outStream.write(xmlbyte);
    总结:
    --我们使用的是用HTML的方式传输文件,这个方式只能传输一般在5M一下的文件.
    --传输大文件不适合用HTML的方式,传输大文件我们要面向Socket编程.确保程序的稳定性.

  • 相关阅读:
    对数损失函数(Logarithmic Loss Function)的原理和 Python 实现
    ffmpeg 简介及使用
    数据预处理(Python scikit-learn)
    检查 NaN 数据值 (C/C++/Python 实现)
    数据正规化 (data normalization) 的原理及实现 (Python sklearn)
    matplotlib.pyplot 导引
    在 O(1) 时间删除链表结点(C 和 Python 实现)
    安装 Python IDLE (Linux)
    打印 1 到最大的 n 位数(C++ 和 Python 实现)
    七种RAID技术
  • 原文地址:https://www.cnblogs.com/dreamworlds/p/5374263.html
Copyright © 2020-2023  润新知