需求:从网络上获取图片验证码,原生httpconnection,代码如下:
注意:一定不要写到主线程里面,android 不支持主线程访问网络
private class GetImagTask extends AsyncTask<Integer, Integer, Integer>{
@Override
protected Integer doInBackground(Integer... params) {
URL imgUrl = null;
Bitmap bitmap = null;
try {
imgUrl = new URL("http://192.168.54.82:8080/login.do?method=getimg");
HttpURLConnection conn = (HttpURLConnection)imgUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
img_yzm.setImageBitmap(bitmap);
return null;
}
}
这样就可以显示出来图片了