1. 程式人生 > >HttpUtils.java 網絡下載工具類

HttpUtils.java 網絡下載工具類

arr tle sys 字節數 stream ati reat package you

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");

}

}

HttpUtils.java 網絡下載工具類