package com.bwie.day3;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.CookieStore;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private TextView txtTitle;
private ListView lvNews;
private static final String URL = "http://www.xieast.com/api/travel.php";
private static final String URLT = "https://www.toutiao.com/hot_words";
private List<String> datas;
private List<News.NewslistBean> list;
// String[] arr = {
// "火箭签约安东尼",
// "山东暴雨预警",
// "黄晓明 股票操纵",
// "韩学臣被判无期",
// "茅台致歉",
// "阅文收购新丽传媒",
// "哈登对女子动粗",
// "南京楼市调控新政",
// "怪物猎人世界下架",
// "江西彭小峰被批捕"
// };
// String arr = "";
private int index = 0;
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
txtTitle.setText(datas.get(index%datas.size()));
index++;
sendEmptyMessageDelayed(1,3000);
}
};
private NewsAdapter adapter;
@SuppressLint("StaticFieldLeak")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvNews = findViewById(R.id.lv_news);
datas = new ArrayList<String>();
list = new ArrayList<>();
adapter = new NewsAdapter(this,list);
lvNews.setAdapter(adapter);
new AsyncTask<String,Intent,String>(){
@Override
protected String doInBackground(String... strings) {
String result = getFromHttpClient(strings[0]);
return result;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (!TextUtils.isEmpty(s)){
Gson gson = new Gson();
News news = gson.fromJson(s,News.class);
list.clear();
list.addAll(news.getNewslist());
adapter.notifyDataSetChanged();
}
}
}.execute(URL);
txtTitle = findViewById(R.id.txt_title);
new Thread(){
@Override
public void run() {
try {
//1.创建URL
URL url=new URL("https://www.toutiao.com/hot_words/");
//2.打开连接,进行请求
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
//3.设置
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
//4.判断响应码
if(connection.getResponseCode()==200){
//5.得到返回结果
InputStream stream=connection.getInputStream();
//将流转换成字符串
String str=streamToString(stream);
//进行解析
getJsonData(str);
//发送一个空消息
handler.sendEmptyMessage(1);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
public void getJsonData(String str){
try {
//Gson 原生解析
JSONArray array=new JSONArray(str);
for(int i=0;i<array.length();i++){
String data=array.optString(i);
datas.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public String streamToString(InputStream inputStream){
StringBuilder builder=new StringBuilder();
try {
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
String con;
while ((con=bufferedReader.readLine())!=null){
builder.append(con);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
public static String getFromHttpClient(String urlString){
String result = "";
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(false);
connection.setConnectTimeout(3000);
connection.connect();
int code = connection.getResponseCode();
if (code == 200){
InputStream is = connection.getInputStream();
result = getStringFromInputStream(is);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static String getStringFromInputStream(InputStream is){
String result = "";
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int length = -1;
byte[] buffer = new byte[1024];
while ((length = is.read(buffer,0,buffer.length)) != -1){
baos.write(buffer,0,length);
baos.flush();
}
result = baos.toString();
baos.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}