package com.example.day_02_httpurlconnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ListView;
import android.widget.Toast;
import com.example.adapter.MyAdapter;
import com.example.vo.Result;
import com.example.vo.Root;
import com.google.gson.Gson;
public class MainActivity extends Activity {
// private String path = "http://op.juhe.cn/onebox/news/query?q=普京&key=f2219bf102195209a3db41a58ce0b180";
List<Result> list = new ArrayList<Result>();
Handler handler = new Handler(){
public void handleMessage(Message msg) {
Root root = (Root)msg.obj;
list.addAll(root.getResult());
lv.setAdapter(new MyAdapter(MainActivity.this,list));
Toast.makeText(MainActivity.this, list.get(1).getTitle(), Toast.LENGTH_SHORT)
.show();
};
};
private ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lv);
new Thread(){
@Override
public void run() {
getData();
}
}.start();
}
private void getData() {
try {
String name = URLEncoder.encode("普京","UTF-8");
// 设置路径
URL url = new URL("http://op.juhe.cn/onebox/news/query?q="+name+"&key=f2219bf102195209a3db41a58ce0b180");
// 得到HttpURLConnection对象
HttpURLConnection httpConnection = (HttpURLConnection) url
.openConnection();
// 设置连接超时
httpConnection.setConnectTimeout(5000);
// 设置读取超时
httpConnection.setReadTimeout(5000);
// 设置请求的方法
httpConnection.setRequestMethod("GET");
// 开始正式联网
httpConnection.connect();
// 得到状态码
int code = httpConnection.getResponseCode();
// 判断是否连接成功
if (code == 200) {
// 获得数据的流
InputStream inputStream = httpConnection.getInputStream();
// 通过BufferedReader读取内容
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
String str;
StringBuffer stringBuffer = new StringBuffer();
//通过循环读取数据
while((str = bufferedReader.readLine()) != null){
stringBuffer.append(str);
}
String data = stringBuffer.toString();
System.out.println(data);
//得到Gson对象
Gson gson = new Gson();
//将得到的数据解析出来
Root root = gson.fromJson(data, Root.class);
//将数据发送给主线程
Message msg = Message.obtain();
msg.obj = root;
handler.sendMessage(msg);
} else {
Toast.makeText(MainActivity.this, "请求失败!", Toast.LENGTH_SHORT)
.show();
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
}