- HttpURLConnection
- 是 Java 里面 Http 请求操作的基本类
- ByteArrayOutputStream
- 可以将一些二进制数据写出到一个内存块里
- 这个流不需要关闭
连接网络
// 获取用户的输入信息,连接服务器,获取网页源码,展示到界面上
public void click(View view) {
// System.out.println("MainActivity.click,");
// 获取用户输入的地址
String urlStr = et_url.getText().toString();
// 连接服务器,获取网页源码
try {
// 1. 创建 URL 地址对象
URL url = new URL(urlStr);
// 2. 获取网络操作的工具类
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 3. 设置请求参数
connection.setRequestMethod("GET");// GET 必须大写
connection.setConnectTimeout(5000);
// 4. 发起请求,获取服务器的响应码
int code = connection.getResponseCode();
// System.out.println("code="+code);
// 5. 判断请求码的数值。 200 连接成功 404 网页不存在 206 部分成功
if (code == 200) {
// 6. 连接成功.获取服务器的输入流
InputStream inputStream = connection.getInputStream();
// 7. 从输入流读取数据,获取到网页源码的字符串
String content = StreamUtils.readStream(inputStream);
// 8. 将获取的字符串显示到界面上
tv_content.setText(content);
}
} catch (Exception e) {
e.printStackTrace();
}
}
从输入流获取字符串
// 从输入流读取数据,并且将二进制数据转换成字符串
public static String readStream(InputStream inputStream) throws Exception {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream(); 该类可以直接讲流写到内存中,toByteArray方法将二进制内容转为byte数组,该流不需要关闭流。
while ((len = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
inputStream.close();
return new String(baos.toByteArray());
}
自定义控件:封装网络图片加载功能
/* 根据提供的 urlStr 自动联网下载图片,并显示出来 */
public void setImageUrl(final String urlStr) {
new Thread() {
public void run() {
try {
// 1. 创建 Url
URL url = new URL(urlStr);
// 2. 获取网络连接对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 3. 设置连接参数
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
// 4. 获取服务器连接状态码
int code = connection.getResponseCode();
if (code == 200) {
// 5. 连接成功获取服务器返回值
InputStream in = connection.getInputStream();
// 6. 将服务器返回值转换成图片
Bitmap bitmap = BitmapFactory.decodeStream(in);
// 将图片显示出来
Message msg = Message.obtain();
msg.obj = bitmap;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
// 在主线程更新图片
Bitmap bitmap = (Bitmap) msg.obj;
setImageBitmap(bitmap);// 当前类就是要显示图片的控件
};
};