import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Handler mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//数据源
ResultData data= (ResultData) msg.obj;
List<ResultData.ResultBean.DataBean> data1 = data.getResult().getData();
//3.更新Ui控件 ,设置适配器
MyAdapter adapter=new MyAdapter(MainActivity.this,data1);
listView.setAdapter(adapter);
}
};
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.lv);
//1.开启子线程
new Thread(){
@Override
public void run() {
requestNetData();
}
}.start();
}
private void requestNetData() {
try {
//1.创建URL对象 3.
URL url=new URL("http://v.juhe.cn/toutiao/index");
//2.打开连接
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//3.设置
urlConnection.setRequestMethod("POST");//1.修改方式POST 方式一定要大写
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
//4.设置向服务器发送消息体信息 2
urlConnection.setDoOutput(true);
//参数信息
String params="type=top&key=597b4f9dcb50e051fd725a9ec54d6653";
urlConnection.getOutputStream().write(params.getBytes());//将字符串转换成字节数据,发送给服务器
//4.判断响应码
int responseCode = urlConnection.getResponseCode();
if(responseCode==200){
//5.获取数据,以输入流的形式返回
InputStream inputStream = urlConnection.getInputStream();
String data = streamToString(inputStream);
//进行解析
Gson gson=new Gson();
ResultData resultData = gson.fromJson(data, ResultData.class);
//2.创建handler对象,发消息给主线程
Message msg=Message.obtain();
msg.obj=resultData;
mHandler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//将流转换成字符串
public String streamToString(InputStream stream){
StringBuilder builder=null;
try {
BufferedReader reader=new BufferedReader(new InputStreamReader(stream));
String str;
builder = new StringBuilder();
while ((str=reader.readLine())!=null){
builder.append(str);
}
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString() ;
}
}