Android 网络编程–get图片、html并显示到控件
一、get图片显示到控件
注:
-
is = conn.getInputStream(); 先将is转为输出流os,具体为: is = conn.getInputStream(); Log.d(TAG,“is.available—>”+is.available()); baos = new ByteArrayOutputStream(); byte[] bytes=new byte[1024]; int len; while((len=is.read(bytes))!=-1){ baos.write(bytes,0,len); } 万金油的is转os代码,获取html、图片、纯文本都可。ps:纯文本一般用BufferedRead. . 读入到输入流,转为输出流后,直接调用Bitmap,BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length); -
显示控件 image.setImageBitmap(bitmap); public void hucGethtml() throws Exception { HttpURLConnection conn; ByteArrayOutputStream baos; InputStream is; Bitmap bitmap; //1.确定url链接
String baseUrl="图片路径";
URL url = new URL(baseUrl);
Log.d(TAG,"baseUrl--->"+baseUrl);
//2.创建conn打开链接,后续操作对象都是conn
conn = (HttpURLConnection) url.openConnection();
//3.设置请求方式:get, 延时:6s
conn.setRequestMethod("GET");
conn.setConnectTimeout(6000);
//4.判断状态码,200表示正常,可进行下一步操作
Log.d(TAG,"状态码--->"+conn.getResponseCode());
if (conn.getResponseCode()==HttpURLConnection.HTTP_OK){
//5.获取输入流
is = conn.getInputStream();
Log.d(TAG,"is.available--->"+is.available());
baos = new ByteArrayOutputStream();
byte[] bytes=new byte[1024];
int len;
while((len=is.read(bytes))!=-1){
baos.write(bytes,0,len);
}
Log.d(TAG,"baos.toByteArray--->"+baos.toByteArray());
Log.d(TAG,"baos.toString--->"+baos.toString());
bitmap = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length);
//专门用于更新显示控件视图的线程
runOnUiThread(new Runnable() {
@Override
public void run() {
//6.展示获得的html
ImageView image=findViewById(R.id.image);
image.setImageBitmap(bitmap);
// Toast.makeText(TestActivity01.this, baos.toString(), Toast.LENGTH_SHORT).show(); } }); //关闭资源
baos.close();
is.close();
conn.disconnect();
}else{
throw new RuntimeException("状态码为"+conn.getResponseCode()+",请求url失败");
}
}
二、get html显示到控件
代码同上,获取到输出baos后直接baos.toString即可
总结
1.无论是图片还是html还是其他,都要获取到is后,转成os,才能输出想要得内容
2.对于图片想要显示到控件
bitmap = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length);
再用新线程或者handle进行赋值
image.setImageBitmap(bitmap);
|