注意:进行Http网络请求需要在AndroidManifest.xml中允许网络权限。
AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
布局文件,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"
tools:context="${relativePackage}.${activityClass}" >
<Button
android:id="@+id/mSelect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="请求图片" />
<ImageView
android:id="@+id/mImage"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
MainActivity.java:
private Button mSelect;
private ImageView mImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSelect = (Button)findViewById(R.id.mSelect);
mImage = (ImageView)findViewById(R.id.mImage);
mSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Bitmap bitmap = getImageFromServer("https://网络图片地址");
Message msg = new Message();
msg.what = 1;
msg.obj = bitmap;
handler.sendMessage(msg);
}
}).start();
}
});
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
Bitmap bitmap = (Bitmap)msg.obj;
mImage.setImageBitmap(bitmap);
break;
case 2:
String info = (String)msg.obj;
Toast.makeText(MainActivity.this,info,Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
};
private Bitmap getImageFromServer(String path){
try {
//1、获得统一资源定位符
URL url = new URL(path);
//2、装化成http网络请求
HttpURLConnection connection =(HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET"); //默认是get请求,当写POST时便是post请求
connection.setConnectTimeout(5000); //设置访问超时的时间。
if(connection.getResponseCode()==200){ //获取响应码
//获取资源类型
String type = connection.getContentType();
//获取资源的长度
int length = connection.getContentLength();
Log.d("图片的资源:","type==="+type+"length==="+length);
//3、获取网络输入流
InputStream is = connection.getInputStream();
//4、将流转换成bitmap对象
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
}
}catch (Exception e){
Message msg = Message.obtain();
msg.what = 2;
msg.obj = "图片访问失败,请检查网络";
handler.sendMessage(msg);
}
return null;
}