欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android 之 网络访问服务器,解析JSON数据

程序员文章站 2022-04-30 19:36:49
...
提示:在访问网络,或者服务器的数据一定要注意 网络权限的声明:
	<uses-permission android:name="android.permission.INTERNET"/>


package com.sun.parsejsondata;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.test.AndroidTestCase;
import android.util.Log;

/*{
    "index_num":"121286",
    "total":300,
    "result_num":10,
    "web_url":"http://www.aibang.com",
    "wap_url":"http://wap.aibang.com",
    "bizs":{
        "biz":[{
            "id":"19180584-418982077",
            "name":"北京饭店",
            "addr":"东城区东长安街号(近王府井大街)",
            "tel":"4006778919-1011",
            "cate":"宾馆酒店;美食;其他美食;五星级酒店;婚宴酒店;结婚",
            "rate":4,
            "cost":0,
            "desc":"北京饭店始建于年,位于北京市中心,步行五,毗邻皇宫紫禁城,与繁华的...",
            "dist":"-1",
            "lng":"116.411096",
            "lat":"39.9084880",
            "img_url":"http://img0.aibangjuxin.com/ipic/15f6cfa4e1cc98cf_8.jpg"
        },
        ...
        ]
    }
}*/


/**
 *  获取网络数据 -- json 格式,并进行解析
 * @author Administrator
 *
 */
public class ParseJson  {

	/**
	 * 解析JSON 数据
	 * @throws Exception 
	 */
	public void parseJson(String jsonStr) throws Exception{
		
		JSONObject root = new JSONObject(jsonStr);
		
		// 编号
		String index_num = (String) root.get("index_num");
		int total = root.getInt("total");
		int result_num = root.getInt("result_num");
		
		JSONObject bizsO = root.getJSONObject("bizs"); 
		JSONArray arr = bizsO.getJSONArray("biz");
		for (int i = 0; i < arr.length(); i++) {
			JSONObject bizs_ =arr.getJSONObject(i);
			String id = bizs_.getString("id");
			String addr = bizs_.getString("addr");
			Log.i("msg","编号:"+id+"',地址"+addr);
		}
		
	}
	
	/**
	 * 访问网络数据
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public String accessIntent() throws Exception{
		
		// 请求服务器地址
		String path = "http://169.254.111.39:8080/myjson.html";
		
		// Get 方式进行请求
		HttpGet httpGet = new HttpGet(path);
		
		// 默认客户端
		HttpClient httpClient = new DefaultHttpClient();
		
		// 请求响应
		HttpResponse httpResponse = httpClient.execute(httpGet);
		
		// 判断响应结果
		if(httpResponse.getStatusLine().getStatusCode() == 200){ // 响应成功
			
			HttpEntity httpEntity = httpResponse.getEntity(); 
			String result = EntityUtils.toString(httpEntity, "gbk");
			Log.i("msg",result);
			return result;
		}
		
		return null;
	}	
	
}


post的请求方式:

public class HttpURLActivity extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        System.out.println("start url..."); 
        String url = "http://192.168.2.112:8080/JustsyApp/Applet"; 
        // 第一步,创建HttpPost对象 
        HttpPost httpPost = new HttpPost(url); 
 
        // 设置HTTP POST请求参数必须用NameValuePair对象 
        List<NameValuePair> params = new ArrayList<NameValuePair>(); 
        params.add(new BasicNameValuePair("action", "downloadAndroidApp")); 
        params.add(new BasicNameValuePair("packageId", "89dcb664-50a7-4bf2-aeed-49c08af6a58a")); 
        params.add(new BasicNameValuePair("uuid", "test_ok1")); 
 
        HttpResponse httpResponse = null; 
        try { 
            // 设置httpPost请求参数 
            httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); 
            httpResponse = new DefaultHttpClient().execute(httpPost); 
            //System.out.println(httpResponse.getStatusLine().getStatusCode()); 
            if (httpResponse.getStatusLine().getStatusCode() == 200) { 
                // 第三步,使用getEntity方法活得返回结果 
                String result = EntityUtils.toString(httpResponse.getEntity()); 
                System.out.println("result:" + result); 
                T.displayToast(HttpURLActivity.this, "result:" + result); 
            } 
        } catch (ClientProtocolException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
        System.out.println("end url..."); 
        setContentView(R.layout.main); 
    } 
}