利用Handler实现网络数据下载Json并转换成实体类的封装

NetWorkRunable类

用于实现子线程下载网络数据, 并转换成Json字符串, 然后通过Gson实现与实体类的转换, 所以必须导入Google的Gson包, 并写自己的实体类(记得加上注解)

/**
 * Created by Lulu on 2016/9/1.
 * 封装访问网络的类, Handler实现
 */
public class NetWorkRunable<T> implements Runnable, Handler.Callback {

    private final Handler handler;
    private String url;
    private Class<T> t;
    private MyCallback<T> callback;

    public NetWorkRunable(String url, Class<T> t, MyCallback<T> callback) {
        this.url = url;
        this.t = t;
        this.callback = callback;
        //Looper.getMainLooper(): 因为Handler如果不指定, 得到的是当前线程的looper
        //现在直接将主线程的Looper传入!!!
        handler = new Handler(Looper.getMainLooper(), this);//现在它一定在主线程中执行
    }

    @Override
    public boolean handleMessage(Message msg) {
        Object o = msg.obj;
        switch (msg.what) {
            case 0:
                callback.onSuccess((T) o);
                break;
            case 1:
                callback.onFailed((Exception) o);
                break;
        }
        //消息不再传递, 被截获
        return true;
    }
    public interface MyCallback<S> {
        void onSuccess(S s);
        void onFailed(Exception e);
    }

    @Override
    public void run() {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            int code = connection.getResponseCode();
            if (code == 200) {
                InputStream is = connection.getInputStream();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] buffer = new byte[102400];
                int length;
                while ((length = is.read(buffer)) != -1) {
                    bos.write(buffer, 0, length);
                }
                String str = bos.toString("UTF-8");
                Gson gson = new Gson();
                handler.obtainMessage(0, gson.fromJson(str, t)).sendToTarget();
            } else {
                handler.obtainMessage(1, new RuntimeException("服务器异常"));
            }
        } catch (IOException e) {
            handler.obtainMessage(1, new RuntimeException("IO出现异常")).sendToTarget();
            e.printStackTrace();
        }
    }
}

测试实体类

public class Entry {
    @SerializedName("title")
    private String title;
    @SerializedName("message")
    private String message;

    ...//省略getter和setter方法
}

测试Activity

class MainActivity extends AppCompatActivity implements NetWorkRunable.MyCallback<Entry> {
    private static final String TAG = MainActivity.class.getSimpleName();
    private WebView webView;
    private static final String CSS = "<style>img{max-width:100%} </style>";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = (WebView) findViewById(R.id.main_web);
        String url = "http://www.tngou.net/api/top/show?id=106";
        new Thread(new NetWorkRunable<>(url, Entry.class, this)).start();
    }
    @Override
    public void onSuccess(Entry entry) {
        Log.d(TAG, "onSuccess: " + entry.getTitle());
        setTitle(entry.getTitle());
        webView.loadDataWithBaseURL("", CSS + entry.getMessage(), "text/html; charset=utf-8", "UTF-8", null);
    }
    @Override
    public void onFailed(Exception e) {
        webView.loadDataWithBaseURL("", e.getMessage(), "text/html; charset=utf-8", "UTF-8", null);
    }
}

效果图

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值