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 list = bean.getResult().getData();
listView.setAdapter(new MyAdapter(MainActivity.this, (ArrayList) 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();
}

你可能感兴趣的:(Gson解析——Get请求数据)