@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview=(ListView)findViewById(R.id.listview);
new Thread(){
public void run() {
getInfo();
}
}.start();
}
private void getInfo() {
//接口地址
String uri="http://apis.juhe.cn/goodbook/catalog";
//得到httpclient对象
DefaultHttpClient httpClient = new DefaultHttpClient();
//设置请求方式httppost
HttpPost httpPost = new HttpPost(uri);
//创建需要携带参数的集合
ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
//通过键值对传递服务器需要的参数
list.add(new BasicNameValuePair("key", "cca134699ab46a8322a322c8c011449a"));
try {
//得到实体对象,并设置编码集
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list);
//将实体设置给httpPost,用于传递给服务器
httpPost.setEntity(entity);
//执行要访问的网络请求
HttpResponse response = httpClient.execute(httpPost);
//得到状态行
StatusLine statusLine = response.getStatusLine();
//得到状态吗
int statusCode = statusLine.getStatusCode();
//通过状态吗判断是否链接成功
if(statusCode==200){
//得到服务器返回的数据,包含着需要的数据(json,xml)
HttpEntity entity2 = response.getEntity();
//将实体转化成String类型
String string = EntityUtils.toString(entity2);
//用gson解析json
Gson gs=new Gson();
Bean fromJson = gs.fromJson(string, Bean.class);
final ArrayList<Result> result = fromJson.result;
//在 runOnUiThread中用adapter进行展示数据
runOnUiThread(new Runnable() {
@Override
public void run() {
listview.setAdapter(new BeAdapter(MainActivity.this,result));
}
});
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};