展会信息港展会大全

Android发出HTTP请求,解析返回的JSON (PHP)
来源:互联网   发布日期:2016-01-13 21:57:49   浏览:3247次  

导读: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.......

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.android100.org/");

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;

}

}

}

赞助本站

人工智能实验室

相关热词: HTTP JSON PHP

相关内容
AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港