首页 > 代码库 > HttpUtils.java 网络下载工具类

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

}

}

HttpUtils.java 网络下载工具类