HttpUtils.java 網絡下載工具類


package Http;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
* 網絡下載工具類
* 功能:下載字節數組,下載文本數據
* 下載數字數組(文本 圖片 mp3)
* 下載文本數據
* Created by lxj-pc on 2017/6/27.
*/
public class HttpUtils {
public static byte[] get(String url) throws IOException {
//網絡下載
HttpURLConnection conn = (HttpURLConnection) new URL
(url).openConnection();

InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = null;

if (conn.getResponseCode() == 200) {
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[8 * 1024];//8k
int len = -1;

//獲取資源的總長度
int totalLen = conn.getContentLength();
int curLen = 0;
while ((len = is.read(buffer)) != -1) {

baos.write(buffer, 0, len);
//3.計算下載 進度
curLen += len;
int p = curLen * 100 / totalLen;
System.out.println("jindu" + p + "%");

}

is.close();
conn.disconnect();

}

return baos.toByteArray();
}

public static String getText(String url) throws Exception{


return new String(get(url), "utf-8");

}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM