关闭

异步请求网络数据

标签: 异步请求网络异步
632人阅读 评论(0) 收藏 举报
分类:

package com.bwie.main;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.ImageLoader;

public class MyAsyncTask extends AsyncTask String, String, String> {

private String str;
private ImageView image;
public MyAsyncTask(ImageView image) {
    // TODO Auto-generated constructor stub
    this.image = image;
}

@Override
protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    // 请求网络
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(params[0]);
    try {
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        str = EntityUtils.toString(entity, "gbk");
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return str;
}

@Override
protected void onPostExecute(String result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    String path = "http://172.17.29.120/localuser/ljy/hengbo/images/ani_sun_sunny.png";
    ImageLoader imageLoader = ImageLoader.getInstance();
    imageLoader.displayImage(path, image);
}

}
//Main活动

// 请求JSON数据
public void ShowJson() {
// 异步加载数据
MyAsyncTask asyncTask = new MyAsyncTask(image);
try {
// 给路径之后必须要给.get()否则获取不了数据
String str = asyncTask.execute(path).get();

        Gson gson = new Gson();
        GvRoot gvRoot = gson.fromJson(str, GvRoot.class);
        list = gvRoot.getData();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:14610次
    • 积分:375
    • 等级:
    • 排名:千里之外
    • 原创:24篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章存档