<span style="font-family:Comic Sans MS;font-size:18px;">package com.example.week4_day2_handledemo1;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
*
* 网络图片下载工具类
*
*/
public class HttpIntenet {
/**
* 判断是否有网络
*/
public static boolean isNet(Context context) {
// 得到网络管理者
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null) {
return true;
} else {
return false;
}
}
/**
* 开启网络连接,下载图片
*
* @param path
* @return
*/
public static byte[] httpintent(String path) {
HttpClient httpclient = new DefaultHttpClient(); // 创建http请求客户端
HttpGet httpget = new HttpGet(path); // 设置get请求
ByteArrayOutputStream out = new ByteArrayOutputStream();// 把得到的内容放入输出流中
try {
HttpResponse httpresponse = httpclient.execute(httpget);// 执行请求
if (httpresponse.getStatusLine().getStatusCode() == 200) { // 判断网络请求是否成功
InputStream inputStream = httpresponse.getEntity()// 得到内容--输入流
.getContent();
byte[] buffer = new byte[1024];
int tmp = 0;
while ((tmp = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, tmp);// 读取tmp字节存入输出流中
out.flush();// 刷新流
}
}
return out.toByteArray();// 返回一个byte[]数据
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
</span>
网络图片下载工具类
最新推荐文章于 2023-11-22 15:21:36 发布