import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
private Button button;
private ImageView img;
private Handler mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//显示图片
Bitmap bitmap=(Bitmap) msg.obj;
img.setImageBitmap(bitmap);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ctrl+alt+f:设置成员变量
button = findViewById(R.id.btndown);
img = findViewById(R.id.img);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//1.进行网络请求,属于耗时任务。。。。开启一个子线程
new Thread(){
@Override
public void run() {
//使用java.net包下的httpurlconnention
reqestNetData();
}
}.start();
}
});
}
private void reqestNetData() {
//1.创建一个Url对象 ctrl+alt+t
try {
URL url=new URL("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1514265095973&di=2a7c0fef6b89033033b9aee3bdfebf3c&imgtype=0&src=http%3A%2F%2Fimg5.duitang.com%2Fuploads%2Fitem%2F201602%2F08%2F20160208202129_vBMP2.jpeg");
//2. 打开连接 alt+enter自动补全 HttpURLConnection 继承自 URLConnection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//3.进行设置
urlConnection.setRequestMethod("GET");//设置请求方式
urlConnection.setConnectTimeout(5000);//连接超时时间
urlConnection.setReadTimeout(5000);//读取超时时间
//4.判断响应码
int responseCode = urlConnection.getResponseCode();
if(responseCode==200){//正常
//5.获取数据
InputStream inputStream = urlConnection.getInputStream();
//将流转换成二进制图片对象
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
//显示图片
//img.setImageBitmap(bitmap);
Message msg=Message.obtain();
msg.obj=bitmap;
mHandler.sendMessage(msg);
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}