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);
}
}