网络上获取头条的数据
private void getTouTiao() {new Thread(){
@Override
public void run() {
try {
URL url = new URL("http://www.toutiao.com/hot_words/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
//获取
int responseCode = connection.getResponseCode();
if (responseCode == 200){
InputStream inputStream = connection.getInputStream();
//将字节流装换为字符串
String json = streamToString(inputStream,"utf-8");
//字符串发送到主线程解析
Message message = Message.obtain();
message.what = 0;
message.obj = json;
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
Handler
private int index = 0;
//写一个集合记录所有的头条数据
private List<String> list = new ArrayList<>();
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what == 0){
String json = (String) msg.obj;
Log.i("json---",json);
//解析...android中json格式的数据只有两种,,一种是{}对应的,解析出来是对象;;;一种是[]对应的,这种是数组或者集合
//1.集合或者数据在json原生解析,使用的JSONArray这个类...{}对应的在原声解析里面是JSONObject
Gson gson = new Gson();
Type type = new TypeToken<List<String>>() {}.getType();
List<String> jsonList = gson.fromJson(json,type);
Log.i("----",jsonList.size()+"长度");
//2.使用gson解析数组格式的json字符串
try {
JSONArray jsonArray = new JSONArray(json);
//遍历这个json格式的数组
for (int i=0;i<jsonArray.length();i++){
String string = jsonArray.getString(i);
//添加到集合里面去
list.add(string);
}
//设置第一条数据的显示
text_toutiao.setText(list.get(index));
//发送一个延时的消息
handler.sendEmptyMessageDelayed(1,3000);
} catch (Exception e) {
e.printStackTrace();
}
}else if (msg.what == 1){
//接收到延时消息
index ++;
//取余
index = index%list.size();
text_toutiao.setText(list.get(index));
//发送一个延时的消息
handler.sendEmptyMessageDelayed(1,3000);
}
}
};