首页 > 其他 > 详细

请求网络的图片

时间:2015-03-04 00:49:52      阅读:368      评论:0      收藏:0      [点我收藏+]

首先发起一个网络请求,请求到图片的url后再去请求图片。

 

请求图片后返回到主线程处理

 

private Runnable myRun;
private DefaultHttpClient httpClient;

private Object result;

public void request(final String url) {



Log.i("mjm", "request : " + url);
myRun = new Runnable() {


@Override
public void run() {
Log.i("TAG", url);
httpClient = new DefaultHttpClient();
// 设置网络连接超时时间
httpClient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
// 设置网络socket通信超时时间
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
3000);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(httpGet);
int code = httpResponse.getStatusLine().getStatusCode();
// 请求成功
if (HttpStatus.SC_OK == code) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
httpResponse.getEntity().writeTo(baos);
result = new String(baos.toByteArray()).trim();
Log.i("TAG", result.toString());
loadImageFromUrl(result.toString());
} else {// 请求失败
httpGet.abort();
result = "fail";
Log.i("TAG", result.toString());
}
} catch (Exception e) {// 解码异常
e.printStackTrace();
}
}
};
new Thread(myRun).start();

}

 

 

public void loadImageFromUrl(final String url) {
Log.i("mjm", "loadImageFromUrl : " + url);
myRun = new Runnable() {


@Override
public void run() {
// TODO Auto-generated method stub
Bitmap bitmap = null;
URL u = null;
HttpURLConnection conn = null;
InputStream is = null;
try {
u = new URL(url);
conn = (HttpURLConnection) u.openConnection();
is = conn.getInputStream();
Log.i("mjm", "is : " + is.toString());
bitmap = BitmapFactory.decodeStream(is);
mLoadImageCallBack.onSuccess(bitmap);
} catch (Exception e) {
Log.i("mjm", "false : " + e.toString());
mLoadImageCallBack.onFail(e.toString());
}
}
};
new Thread(myRun).start();
}

请求网络的图片

原文:http://www.cnblogs.com/moreking/p/4312204.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!