การคัดลอกรหัสมีดังนี้:
แพ็คเกจ com.hongyuan.test;
นำเข้า Java.io.File;
นำเข้า Java.io.FileOutputStream;
นำเข้า java.io.ioException;
นำเข้า Java.io.InputStream;
นำเข้า Java.io.OutputStream;
นำเข้า java.net.httpurlconnection;
นำเข้า Java.net.Malformedurlexception;
นำเข้า java.net.url;
นำเข้า java.net.urldecoder;
ชั้นเรียนสาธารณะ Filedownload {
สตริงสุดท้ายคงที่ local_path = "d:/";
โมฆะคงที่สาธารณะหลัก (สตริง [] args) {
// ที่อยู่ไฟล์ที่จะดาวน์โหลด
สาย fileUrl = "http://211.162.55.16/cdn.baidupcs.com/file/6a73dab7c03023a9835cc73 826-250528-130564002 & เวลา = 1397293108 & sign = fdtaxer-DCB740CCC5511E5E8FEDCFF06B08120 3-MQKOERDTXPYQWWYJKI%2BXKJPXN5K%3D & to = CB & FM = N, B, U, NC & Newver = 1 & Expires = 139 7297563 & RT = SH & R = 854979042 A8%8B%E5%BA%8F%E8%AE% เป็น%e8%ae%a1%20%e7%ac%ac5%e7%89%88.pdf & wshc_tag = 0 & wsiphost = ipdbm ";
inputStream ใน = null;
outputstream out = null;
httpurlConnection conn = null;
ชื่อไฟล์สตริง = null;
พยายาม {
// เริ่มต้นการเชื่อมต่อ
url url = url ใหม่ (fileurl);
conn = (httpurlconnection) url.openconnection ();
conn.setDoInput (จริง);
conn.setDooutput (จริง);
// รับชื่อไฟล์
การจัดการสตริง = conn.getheaderfield ("เนื้อหา-การกระจาย");
ถ้า (disposition! = null &&! "". เท่ากับ (การจัดการ)) {
// รับชื่อไฟล์ตั้งแต่ต้น
filename = disposition.split (";") [1] .split ("=") [1] .replaceall ("/" "," ");
}อื่น{
// รับชื่อไฟล์จากที่อยู่
filename = fileUrl.substring (fileUrl.AlastIndexof ("/")+1);
-
ถ้า (ชื่อไฟล์! = null &&! "". เท่ากับ (ชื่อไฟล์)) {
// ถอดรหัสชื่อไฟล์
filename = urldecoder.decode (ชื่อไฟล์, "UTF-8");
}อื่น{
// หากไม่สามารถเรียกคืนชื่อไฟล์ได้การสร้างแบบสุ่มจะถูกสร้างขึ้น
filename = "ไฟล์ _"+(int) (math.random ()*10);
-
// อ่านข้อมูล
if (conn.getResponsecode () == httpurlConnection.http_ok) {
ไบต์ [] บัฟเฟอร์ = ไบต์ใหม่ [2048];
ใน = conn.getInputStream ();
out = new fileOutputStream (ไฟล์ใหม่ (local_path, ชื่อไฟล์));
จำนวน int = 0;
int เสร็จสิ้น = 0;
ขนาด int = conn.getContentLength ();
ในขณะที่ ((count = in.read (บัฟเฟอร์))! =-1) {
ถ้า (นับ! = 0) {
out.write (บัฟเฟอร์, 0, นับ);
เสร็จสิ้น+= นับ;
System.out.printf ("############################################################ ################### ---->%1 $ .2F %%/N ", (สอง) เสร็จแล้ว/ขนาด*100);
}อื่น{
หยุดพัก;
-
-
-
} catch (malformedurlexception e) {
E.PrintStackTrace ();
} catch (ioexception e) {
E.PrintStackTrace ();
} ในที่สุด{
พยายาม {
out.close ();
in.close ();
conn.disconnect ();
} catch (ioexception e) {
E.PrintStackTrace ();
-
-
-
-