Day_02.com.example.day_02.MainActivity.java
package com.example.day_02;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
/**
* android.permission.INTERNET 添加权限
* */
public class MainActivity extends Activity {
private ImageView img;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
// 显示
img.setImageBitmap((Bitmap) msg.obj);
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取控件
img = (ImageView) findViewById(R.id.img);
}
public void dian(View v) {
// 访问网络开启子线程
new Thread() {
public void run() {
pic();
};
}.start();
}
private void pic() {
// 图片路径
String picPath = "http://img3.redocn.com/tupian/20151111/shouhuigoutouxiangtupian_5294912.jpg";
try {
// 创建url对象
URL url = new URL(picPath);
// 打开连接HttpURLConnection extends URLConnection 遵循http协议
HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
// get 是默认的请求方式
openConnection.setRequestMethod("GET");
// 设置连接服务器的超时时间
openConnection.setConnectTimeout(3000);
// 设置读取内容的超时时间
openConnection.setReadTimeout(3000);
// 得到返回的状态码
int responseCode = openConnection.getResponseCode();
// 进行判断
if (responseCode == 200) {// responseCode==200请求成功
// 拿到服务器返回的数据 以字节流的返回
InputStream inputStream = openConnection.getInputStream();
Log.i("z", inputStream.toString());
// 将流转换成bitmap对象
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// 发送数据
Message obtain = Message.obtain();
obtain.obj = bitmap;
handler.sendMessage(obtain);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="get请求一张图片"
android:onClick="dian" />
<ImageView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>