Android发出HTTP请求,解析返回的JSON

1:php端

echo json_encode($data);

2:Android端

package android.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class Main extends Activity {
	private TextView m_textView;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		JSONObject obj = GetJsonObject();
		StringBuilder sb = new StringBuilder();
		try {
			sb.append("product_id: " + obj.getInt("id") + "/n");
			sb.append("website_name: " + obj.getString("site_name") + "/n");
			sb.append("title: " + obj.getString("title") + "/n");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		m_textView = (TextView) findViewById(R.id.myTextView);
		m_textView.setText(sb.toString());
	}

	private JSONObject GetJsonObject() {
		HttpClient client = new DefaultHttpClient();
		StringBuilder builder = new StringBuilder();
		JSONArray jsonArray = null;
		HttpGet get = new HttpGet("http://www.android-study.com/");
		try {
			HttpResponse response = client.execute(get);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			for (String s = reader.readLine(); s != null; s = reader.readLine()) {
				builder.append(s);
			}
			Log.i("json_str", builder.toString());
			jsonArray = new JSONArray(builder.toString());
			for (int i = 0; i < 2;="" ++i)="" {="" jsonobject="" jsonobject="jsonArray.getJSONObject(i);" log.i("id",="" jsonobject.getint("id")="" +="" "");="" log.i("website_name",="" jsonobject.getstring("site_name"));="" log.i("website_url",="" jsonobject.getstring("site_url"));="" log.i("category",="" jsonobject.getint("category")="" +="" "");="" log.i("title",="" jsonobject.getstring("title"));="" }="" }="" catch="" (exception="" e)="" {="" e.printstacktrace();="" }="" try="" {="" return="" jsonarray.getjsonobject(5);="" }="" catch="" (jsonexception="" e)="" {="" e.printstacktrace();="" return="" null;="" }="" }="" }="">
暂无评论
  • 1:请一针见血的评论。
  • 2:评论需要审核通过后才能显示。
  • 3:评论字数限制在1000字以内。
  • 当前字数:0
热门文章
推荐文章
随机文章
关于本站 - 广告服务 - 版权声明 - 联系我们 - 友情链接 - 网站地图 - 帮助中心