首页 > 代码库 > android网络HttpURLConnection抓取网络图片
android网络HttpURLConnection抓取网络图片
package com.liang.netpicture; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; public class MainActivity extends ActionBarActivity { ImageView iv_main; private final int SUCCESS=0; private final int ERROR=1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv_main = (ImageView) findViewById(R.id.iv_main); //handler接受消息 final Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if(msg.what==SUCCESS){ iv_main.setImageBitmap((Bitmap) msg.obj); }else{ Toast.makeText(MainActivity.this,"抓取失败",Toast.LENGTH_SHORT).show(); } } }; //耗时操作都需要在子线程中完成,并且不能在子线程中更改UI线程的组件状态,需使用Handler进行线程通信 new Thread(new Runnable() { @Override public void run() { Bitmap bitmap = getNetPicture(); Message msg=new Message(); if(bitmap!=null){ msg.what=SUCCESS; msg.obj=bitmap; }else{ msg.what=ERROR; } handler.sendMessage(msg); } }).start(); } private Bitmap getNetPicture() { Bitmap bitmap=null; int responseCode = 0; InputStream is = null; try { URL url = new URL("http://f.hiphotos.baidu.com/image/pic/item/3801213fb80e7beca9bfb6e02d2eb9389b506b4e.jpg"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(10 * 1000); conn.setReadTimeout(5 * 1000); conn.connect(); responseCode = conn.getResponseCode(); if (responseCode == 200) { is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); } } catch (IOException e) { Log.i("test", "访问失败:" + responseCode); e.printStackTrace(); } finally { if (is != null) try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return bitmap; } }需要在清单文件中加入
<!-- 访问网络的权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
android网络HttpURLConnection抓取网络图片
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。