Android上如何获取网络上的图片呢?
步骤:
1.确定图片的路径URL
2.根据url发送http请求
3.设置请求方式
4.得到服务器返回的响应码
5.通过获取输入流获得资源。
具体代码如下:
public class MainActivity extends Activity{
protected static final int CHANGE_UI = 1;
protected static final int ERROR = 2;
private EditText et_path;
private ImageView iv;
//1.在主线程创建消息处理器
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what == CHANGE_UI){
Bitmap bitmap = (Bitmap) msg.obj;
iv.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);
iv = (ImageView) findViewById(R.id.iv);
}
public void click(View v){
final String path = et_path.getText().toString().trim();
if(TextUtils.isEmpty(path))
Toast.makeText(this, "路径不能为空!", Toast.LENGTH_SHORT).show();
else{
new Thread(){
public void run() {
//连接服务器 get请求获取图片
try {
URL url = new URL(path);
//根据url发送http请求
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置请求方式
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestProperty("User-Agent:", " Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; Tablet PC 2.0)");
//得到服务器返回的响应吗
int code = conn.getResponseCode();
if(code==200){
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
//iv.setImageBitmap(bitmap);
//TODO:告诉主线程一个消息 帮我更改界面,内容:bitmap
Message msg = new Message();
msg.what = CHANGE_UI;
msg.obj = bitmap;
handler.sendMessage(msg);
}else{
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
};
}.start();
}
}
}