Gson解析——Get請求資料
運用Handler
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 0:
String data=(String) msg.obj;
Gson gson = new Gson();
JsonBean bean = gson.fromJson(data, JsonBean.class);
List<JsonBean.ResultBean.DataBean> list = bean.getResult().getData();
listView.setAdapter(new MyAdapter(MainActivity.this, (ArrayList<JsonBean.ResultBean.DataBean>) list));
break;
}
}
};
//======OnCreate內部呼叫getData()方法
//獲取資料 private void getData() { new Thread() { @Override public void run() { super.run(); try { URL url = new URL(dataUrl);//獲取路徑 //獲取網路連線 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //獲取請求方式 connection.setRequestMethod(“GET”); //獲取連線超時 connection.setConnectTimeout(3000); //獲取請求嗎 int code = connection.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { //獲取伺服器返回的流 InputStream stream = connection.getInputStream(); //把流轉化為字串CharStreams需要依賴 //implementation ‘com.google.guava:guava:16.0.1’ String s = CharStreams.toString(new InputStreamReader(stream, “UTF-8”)); Message message = Message.obtain(); message.what = HTTP_SUCCESS; message.obj = s; handler.sendMessage(message); } else { Message message = Message.obtain(); message.what = HTTP_ERROR; handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } }.start(); }