码迷,mamicode.com
首页 > 其他好文 > 详细

从服务器获取数据(此处为图片获取)

时间:2015-03-11 02:02:36      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:随笔


public class MainActivity extends Activity {

protected static final int SUCCESS = 1;

private EditText et_id;

private ImageView img;

private Handler handler = new Handler() {


public void handleMessage(Message msg) {


switch (msg.what) {

case SUCCESS:

Bitmap bm = (Bitmap) msg.obj;

img.setImageBitmap(bm);

break;


default:

break;

}

}

};


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

et_id = (EditText) findViewById(R.id.et_id);

img = (ImageView) findViewById(R.id.iv_show);

}


public void downs(View v) {

                //handler+message

//只要是耗时操作,都开辟新的线程

new Thread() {

public void run() {

Bitmap bm = downimg();

Message msg = new Message();

msg.obj = bm;

msg.what = SUCCESS;

handler.sendMessage(msg);


};

}.start();

}


public Bitmap downimg() {


String path = et_id.getText().toString().trim();

HttpURLConnection conn = null;

try {

conn = (HttpURLConnection) new URL(path).openConnection();

conn.setConnectTimeout(5000);

conn.setRequestMethod("GET");

if (conn.getResponseCode() == 200) {

InputStream in = conn.getInputStream();

byte[] b = Utils.write(in);

Bitmap bm = BitmapFactory.decodeByteArray(b, 0, b.length);

return bm;


} else {

Toast.makeText(getApplicationContext(), "请求失败", 2000).show();

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

if (conn != null) {

conn.disconnect();

}

}

return null;

}

}


public class Utils {


public static byte[] write(InputStream in) {


ByteArrayOutputStream out = new ByteArrayOutputStream();

byte[] bytes = new byte[1024];

int len = 0;

try {

while ((len = in.read(bytes)) != -1) {

out.write(bytes, 0, len);


}

return out.toByteArray();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return null;

}


}


本文出自 “Android小笔记” 博客,请务必保留此出处http://dreamwing.blog.51cto.com/9872128/1619145

从服务器获取数据(此处为图片获取)

标签:随笔

原文地址:http://dreamwing.blog.51cto.com/9872128/1619145

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!