android和网络连接相关的类URL,URLConnection,HttpURLConnection,HttpClient

时间:2023-03-09 17:24:45
android和网络连接相关的类URL,URLConnection,HttpURLConnection,HttpClient

这几个类都是用于和服务器端的连接,有些功能都能够实现,关系是:

一、URL

URL标识着网络上的一个资源:该类包含一些URL自身的方法,如获取URL对应的主机名称,端口号,协议,查询字符串外,还有些方法:

openConnection()

Returns a new connection to the resource referred to by this URL.

final InputStream openStream()
Equivalent to openConnection().getInputStream(types).
final Object getContent(Class[] types)
Equivalent to openConnection().getContent(types).

二、URLConnection

该类可以设置相关的请求头参数,发送get或者post请求。
三、HttpURLConnection

URLConnection for http;提供了发送http请求及处理相应的更方便的方法。

四、httpClient

可以认为httpClient就死一个增强版的httpURLCnnection,后者可以做的事前者都可以做,不顾更关注与如何发送请求,接收响应,以及管理连接。

/**
* 该方法能够将url指定的资源转换为byte数组
*
* @param path url对应的地址
* @return 返回字节数组
* @throws Exception
*/
public byte[] getUrlData(String path) throws Exception {
URL url = new URL(path);
// inputstream只能进行读取数据到内存(具体说就是内存中的变量),用于客户端接收服务器端的相应
url.openConnection().setConnectTimeout(3000);
InputStream is = url.openConnection().getInputStream();
byte[] buffer = new byte[1024];
//需要获得数组的时候,这个io流经常使用
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
int len;
while ((len = is.read(buffer)) > 0) {
// 输出流是将内存中的数据(其实就是变量的数据)进行输出,可以输出到文件,转换为字节数组等
bos.write(buffer);
}
return bos.toByteArray();
} catch (Exception e) {
return null;
} finally {
bos.close();
is.close();
} }

例如通过上述方法下载的图片对应的数组,如果希望显示在imageView控件上,借助于bitmap

Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
img.setImageBitmap(bitmap);
//也可以直接从流中常见bitmap
//BitmapFactory.decodeStream(is);

至于保存下载到的图片,借助于文件io,或者bitmap.compress即可。