刚开始学习android为了找到android通过网络获取json数据的例子找了很长的时间,很多都是不行,或者运行不了的例子,下面我就把我整理的完整可以运行的列子展示给大家,同时别忘了在xml开启访问Intent权限,如果没有是不行的。
public class MainActivity extends Activity {
private TextView my_content;
private String url = “http://www.wangzhiguang.com.cn/test.php”;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
my_content = (TextView)findViewById(R.id.my_content);
Button mybutton = (Button)findViewById(R.id.mybutton);
mybutton.setText(“点击按钮获取博客内容”);
mybutton.setOnClickListener(new mybuttonListener());
}
private class mybuttonListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
StringBuffer sb = new StringBuffer();
// 在测试过程中
String body = getContent(url);
JSONArray array = new JSONArray(body);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
sb.append(“id:”).append(obj.getInt(“id”)).append(“\t”);
sb.append(“name:”).append(obj.getString(“name”)).append(“\r\n”);
sb.append(“gender:”).append(obj.getString(“gender”)).append(“\t”);
sb.append(“email:”).append(obj.getString(“email”)).append(“\r\n”);
sb.append(“———————-\r\n”);
}
my_content.setText(sb.toString());
} catch (Exception e) {
// TODO: handle exception
}
}
}
private String getContent(String url) throws Exception {
StringBuilder sb = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpParams httpParams = client.getParams();
// 设置网络超时参数
HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
HttpResponse response = client.execute(new HttpGet(url));
HttpEntity entity = response.getEntity();
if (entity != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), “UTF-8”), 8192);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + “\n”);
}
reader.close();
}
return sb.toString();
}
}