1 package com.my9yu.manager.module.test;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.RandomAccessFile;
7
8 import org.apache.http.HttpEntity;
9 import org.apache.http.HttpResponse;
10 import org.apache.http.client.ClientProtocolException;
11 import org.apache.http.client.HttpClient;
12 import org.apache.http.client.methods.HttpGet;
13 import org.apache.http.impl.client.DefaultHttpClient;
14
15 public class TestHttp {
16 public static void main(String[] args) throws ClientProtocolException, IOException {
17 String url = "http://dl_dir.qq.com/music/clntupate/QQMusic_Setup_85_850.exe";
18 String downFile = "d:\\QQMusic.exe";
19 Long netFileLenght = getNetFileSize(url);
20 Long localFileLenght = getLocalFileSize(downFile);
21
22 if (localFileLenght >= netFileLenght) {
23 System.out.println("已下载完成");
24 return;
25 }
26
27 System.out.println("netFileLenght : " + netFileLenght + " localFileLenght : " + localFileLenght);
28 final HttpClient httpClient = new DefaultHttpClient();
29 httpClient.getParams().setIntParameter("http.socket.timeout", 5000);
30
31 final HttpGet httpGet = new HttpGet(url);
32 httpGet.addHeader("Range", "bytes=" + localFileLenght + "-");
33
34 final HttpResponse response = httpClient.execute(httpGet);
35 final int code = response.getStatusLine().getStatusCode();
36 final HttpEntity entity = response.getEntity();
37 System.out.println(code);
38
39 if (entity != null && code < 400) {
40
41 File file = new File(downFile);
42 RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
43 randomAccessFile.seek(localFileLenght);
44
45 InputStream inputStream = entity.getContent();
46 int b = 0;
47 final byte buffer[] = new byte[1024];
48 while ((b = inputStream.read(buffer)) != -1) {
49 randomAccessFile.write(buffer, 0, b);
50 }
51
52 randomAccessFile.close();
53 inputStream.close();
54 httpClient.getConnectionManager().shutdown();
55 System.out.println("下载完成");
56 }
57 }
58
59 public static Long getLocalFileSize(String fileName) {
60 File file = new File(fileName);
61 return file.length();
62 }
63
64 public static Long getNetFileSize(String url) {
65 Long count = -1L;
66 final HttpClient httpClient = new DefaultHttpClient();
67 httpClient.getParams().setIntParameter("http.socket.timeout", 5000);
68
69 final HttpGet httpGet = new HttpGet(url);
70 HttpResponse response = null;
71 try {
72 response = httpClient.execute(httpGet);
73 final int code = response.getStatusLine().getStatusCode();
74 final HttpEntity entity = response.getEntity();
75 if (entity != null && code == 200) {
76 count = entity.getContentLength();
77 }
78 } catch (ClientProtocolException e) {
79 e.printStackTrace();
80 } catch (IOException e) {
81 e.printStackTrace();
82 } finally {
83 httpClient.getConnectionManager().shutdown();
84 }
85 return count;
86 }
87 }