您的位置:首页 > 理论基础 > 计算机网络

无需第三方的网络下载 GET请求

2016-03-21 20:23 543 查看
不带handle的方法

public class NetWorkUtils {
public static byte[] getBytes(String path){
InputStream is =null;
ByteArrayOutputStream baos =null;
//TODO  下载图片
//params[0]:可变参数的第一个值就是我们要下载的网址
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");

if (connection.getResponseCode() == 200) {

is =  connection.getInputStream();
baos =  new ByteArrayOutputStream();
int len = 0;
byte [] buffer = new byte[1024];

while((len = is.read(buffer)) != -1){
baos.write(buffer, 0, len);
}

byte[] bytes = baos.toByteArray();
return bytes;
}

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
is.close();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}

}
return null;
}
}


///带handle的下载/** * 网络下载的工具类 */

/**
* 网络下载的工具类
*/
public class HttpUtils {

public static final int TIMEOUT = 10000;
//使用handler,负责将回调运送到主线程
private final static Handler handler=new Handler();

/**
*网络下载通过回调,奖数据传递过去,回调的字节数组
* @param path 下载的地址
* @param listener  回调接口
*/
public static void get(final String path, final OnFetchDataListener listener){
//如果其中一个为空,表示下载条件不成熟
if (TextUtils.isEmpty(path)||listener==null){
return;
}
//开启一个线程,在线程里面执行下载图片的操作
new Thread(new Runnable() {
@Override
public void run() {
try {
URL  url=new URL(path);
//打开地址的连接,用的http协议
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(TIMEOUT);
connection.setConnectTimeout(TIMEOUT);
connection.connect();//开启连接
if (connection.getResponseCode()==
HttpURLConnection.HTTP_OK){
//当值为200表示下载成功
InputStream is=connection.getInputStream();
final byte[] ret=is2ByteArray(is);
if (ret!=null){
handler.post(new Runnable() {
@Override
public void run() {
listener.onFetch(ret);
}
});

}
}

} catch (Exception e) {
//打印异常
System.out.println("======>"+e.toString());
e.printStackTrace();
}

}
}).start();

}

/**
* 强输入流转为字节数组
* @param is 输入流
* @return 字节数组
*/
private static byte[] is2ByteArray(InputStream is) {
byte[] ret=null;
if (is==null){
return ret;
}
ByteArrayOutputStream bos=null;
try{
bos=new ByteArrayOutputStream();
int len=0;
byte[] buffer=new byte[1024];
while ((len=is.read(buffer))!=-1){
bos.write(buffer,0,len);
}
ret=bos.toByteArray();

}catch (Exception e){
System.out.println("============>"+e.toString());
e.printStackTrace();
}finally {
try {
bos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return ret;
}

//网络数据接口的回调
public static interface OnFetchDataListener{

void onFetch(byte[] data);
}

}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: