package com.example.newsclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.net.URL;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
public class MainActivity extends Activity {
private ListView mListView;
private static String URL = "http://www.imooc.com/api/teacher?type=4&num=30";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.lv_main);
new NewsAsyncTask().execute(URL);
}
class NewsAsyncTask extends AsyncTask<String, Void, List<NewsBean>> {
@Override
protected List<NewsBean> doInBackground(String... params) {
// TODO Auto-generated method stub
return getJsonData(params[0]);
}
}
private List<NewsBean> getJsonData(String url) {
// TODO Auto-generated method stub
List<NewsBean> newsBeanList = new ArrayList<NewsBean>();
try {
String jsonString = readStream(new URL(url).openStream());
Log.d("xys", jsonString);
} catch (IOException e) {
e.printStackTrace();
}
return newsBeanList;
}
private String readStream(InputStream is) { //InputStream为字节流
InputStreamReader isr;
String result = "";
try {
String line = "";
isr = new InputStreamReader(is, "utf-8"); //将字节流转化为字符流
BufferedReader br = new BufferedReader(isr); //通过BufferedReader将字符流以Buffer的形式读取出来
try {
while ((line = br.readLine()) != null) { //读取字符流之后拼接到result中,连起来就变成字符串
result += line;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}