【例7-2】 从Web 服务器读取图像
设计基于HTTP协议的网络编程,访问一个网络图片并显示输出。

教学视频
布局文件activity_webimg.xml的源代码
<?xml version="1.0" encoding="utf-8"?>
<!--【例7-2】从Web 服务器读取图像文件 -->
<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"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="从Web 服务器读取图像示例"
android:textSize="18sp"/>
<TextView
android:id="@+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="18sp" />
<TextView
android:id="@+id/txt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="18sp" />
<ImageView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:srcCompat="@mipmap/ic_launcher_round" />
</LinearLayout>
控制文件WebImgActivity.java的源代码如下:
package com.example.chap07;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
//【例7-2】从Web 服务器读取图像文件
public class WebImgActivity extends AppCompatActivity {
ImageView img;
TextView txt1, txt2;
Button connBtn;
HttpURLConnection conn = null ;
InputStream inStrem = null;
// 练习的图片来自网络, 有可能被删除,可以自行找一张图
String str = "http://www.szpt.edu.cn/images/pic_5.jpg";
HHandler mHandler = new HHandler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webimg);
img = (ImageView)findViewById(R.id.img);
txt1 = (TextView)findViewById(R.id.txt1);
txt2 = (TextView)findViewById(R.id.txt2);
connBtn = (Button)findViewById(R.id.button);
connBtn.setOnClickListener(new mClick());
}
class mClick implements View.OnClickListener {
public void onClick(View arg0) {
StrictMode.setThreadPolicy(
new StrictMode
.ThreadPolicy
.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build()
);
StrictMode.setVmPolicy(
new StrictMode
.VmPolicy
.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build()
);
getPicture();
}
}
private void getPicture(){
try {
URL url = new URL(str);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if ( conn.getResponseCode() == 200) {
inStrem = conn.getInputStream();
Bitmap bmp= BitmapFactory.decodeStream(inStrem);
mHandler.obtainMessage(0, bmp).sendToTarget();
txt1.setText("(1)建立输入流成功!");
}
}catch(Exception e2) { txt1.setText("(3)IO流失败");}
}
class HHandler extends Handler
{
public void handleMessage(Message msg){
super. handleMessage( msg);
txt2.setText("(2)下载图像成功!");
img.setImageBitmap((Bitmap) msg.obj);
}
}
}
打开AndroidManifest.xml,设置网络权限,配置要启动的Activity类名为WebImgActivity。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.chap07">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true">
<activity android:name=".WebImgActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
例7-2的图片访问网址:https://www.z4a.net/images/2018/07/07/dogshort.jpg, 练习的图片来自网络, 有可能被删除,再推荐一张图 http://www.szpt.edu.cn/images/pic_5.jpg


