通过一个网络图片浏览器的案例展示手机端与服务器端是如何进行通信的,具体步骤如下:
1.创建程序
创建一个ImageView应用程序,指定包名为cn.itcast.imageview,设计用户交互界面,预览效果如下:
图片浏览器界面
对应的布局代码如下:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/ll_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginTop="10dp"
android:orientation="horizontal"
>
<EditText
android:id="@+id/et_path"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginRight="3dp"
android:layout_weight="1"
android:background="#EBEBEB"
android:hint="请输入图片路径"
android:inputType="textUri"
android:paddingLeft="3dp"
android:textColor="#696969"
android:textSize="20sp"
/>
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="4"
android:background="#EBEBEB"
android:onClick="click"
android:text="浏览"
android:textColor="#696969"
android:textSize="20sp"
/>
</LinearLayout>
<ImageView
android:id="@+id/iv_ptc"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/ll_text"
android:scaleType="centerCrop"
/>
</RelativeLayout>
2.编写界面交互代码
界面创建好后,在MainActivity里面编写与界面交互的代码。使用HttpURLConnection获取指定地址的网络图片,并将服务器返回的图片展示在界面上,具体代码如下:
MainActivity.java
package com.czt.imageview;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.UrlQuerySanitizer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
protected static final int CHANGE_UI = 1;
protected static final int ERROR = 2;
private EditText et_path;
private ImageView ivPic;
//主线程创建消息处理器
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg){
if (msg.what == CHANGE_UI){
Bitmap bitmap = (Bitmap) msg.obj;
ivPic.setImageBitmap(bitmap);
}else if (msg.what == ERROR){
Toast.makeText(MainActivity.this,"显示图片错误",Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path = (EditText) findViewById(R.id.et_path);
ivPic = (ImageView) findViewById(R.id.iv_ptc);
}
public void click(View view){
final String path = et_path.getText().toString().trim();
if (TextUtils.isEmpty(path)){
Toast.makeText(this,"图片路径不能为空",Toast.LENGTH_SHORT).show();
}else {
//子线程请求网络,Android4.0以后访问网络不能放在主线程中
new Thread() {
private HttpURLConnection conn;
private Bitmap bitmap;
public void run() {
//连接服务器GET请求获取图片
try {
//创建URL对象
URL url = new URL(path);
//根据URL发送HTTP请求
conn = (HttpURLConnection) url.openConnection();
//设置请求方式
conn.setRequestMethod("GET");
//设置超时时间
conn.setConnectTimeout(5000);
//得到服务器返回的响应码
int code = conn.getResponseCode();
//请求网络成功后返回码是200
if (code == 200) {
//获取输入流
InputStream is = conn.getInputStream();
//将流转换成Bitmap对象
bitmap = BitmapFactory.decodeStream(is);
//将更改主界面的消息发送给主线程
Message msg = new Message();
msg.what = CHANGE_UI;
msg.obj = bitmap;
handler.sendMessage(msg);
} else {
//返回码不等于200请求服务器失败
Message msg = new Message();
msg.what = CHANGE_UI;
msg.obj = bitmap;
handler.sendMessage(msg);
}
}catch (Exception e){
e.printStackTrace();
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
//关闭连接
conn.disconnect();
}
}.start();
}
}
}
在上述代码中,核心代码是第46-88行,这段代码实现或取网络上图片的功能。首先创建一个URL对象,在通过URL对象去获取HttpURLConnection对象,然后设置请求的方法、超时时间,最后获取到了服务器返回的输入流。
3.添加权限
由于网络图片浏览器需要请求网络,因此需要在清单文件中配置相应的权限,代码如下:
···
<uses-permission android:name="android.permission.INTERNET"/>
···
4.运行程序
在文本框中输入任意网络图片的地址,例如http://www.photophoto.cn/m6/018/030/0180300388.jpg,单击"浏览"按钮,运行结果如下:
运行结果
从图中可以看出,使用HttpURLConnection请求指定图片的地址,成功地从服务器获取到了图片信息。