代码如下:
这是类中用HttpURLConnection访问网络,得到输入流。
public class ImageUtil {
/**
* 获取网络地址对应的图片
* @throws MalformedURLException
* @address 地址
* */
public static Bitmap getImage(String address) throws Exception{
//通过代码 模拟器浏览器访问图片的流程
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
//获取服务器返回回来的流
InputStream is = conn.getInputStream();
byte[] imagebytes = getBytes(is);
Bitmap bitmap = BitmapFactory.decodeByteArray(imagebytes, 0, imagebytes.length);
return bitmap;
}
/**
* 把一个inputstream里面的内容转化成一个byte[]
*/
public static byte[] getBytes(InputStream is) throws Exception{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer))!=-1){
bos.write(buffer, 0, len);
}
is.close();
bos.flush();
byte[] result = bos.toByteArray();
System.out.println(new String(result));
return result;
}
}
public class MainActivity extends Activity {
private EditText mEtAddress;
private Button mBtView;
private ImageView mIvView;
private Bitmap bitmap;
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
mIvView.setImageBitmap(bitmap);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEtAddress = (EditText) this.findViewById(R.id.et_address);
mBtView = (Button) this.findViewById(R.id.bt_view);
mIvView = (ImageView) this.findViewById(R.id.iv_image);
mBtView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
String address = mEtAddress.getText().toString().trim();
if ("".equals(address)) {
Toast.makeText(MainActivity.this, "图片地址不能为空",
Toast.LENGTH_SHORT).show();
return;
}
try {
bitmap = ImageUtil.getImage(address);
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
} catch (Exception e) {
if (e instanceof SocketTimeoutException) {
Toast.makeText(MainActivity.this, "网络连接超时",
Toast.LENGTH_SHORT).show();
} else if (e instanceof IOException) {
Toast.makeText(MainActivity.this, "读取数据错误 ",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "未知错误 ",
Toast.LENGTH_SHORT).show();
}
e.printStackTrace();
}
}
}).start();
}
});
}
}
要注意的地方:
1.加上网络权限
2.访问网络的操作,需要放在子线程中进行
3。子线程不能直接跟新UI,所以要用Handler处理