Android解析json數據

package com.org.json;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import com.org.utils.ServerUtils;

public class MainActivity extends Activity {

	private String Url="http://api.k780.com:88/?app=entry.qihu&domain=www.baidu.com&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
	private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        tv=(TextView)findViewById(R.id.TestJson);
 	    //StrictModeUtil.setStrictMode();
 	    
        String text=ServerUtils.getContent(Url);
        try {
			 JSONObject json=new JSONObject(text);
			  
			 String success=json.get("success").toString();
			 
			 JSONObject result=(JSONObject)json.get("result");
			 String website=result.get("website").toString();
			 String entry=result.get("entry").toString();
			 String update=result.get("update").toString();
	 
	      
	         tv.setText(success+entry+update+website);
	         //tv.setMovementMethod(LinkMovementMethod.getInstance());
		} catch (JSONException e) {
			e.printStackTrace();
		}
    }
    
}

 

 

package com.org.utils;

import java.io.IOException;

import org.apache.http.HttpEntity;
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.apache.http.util.EntityUtils;

public class ServerUtils {
	
	/***
	 * 抓取服務端的內容
	 * @param url
	 * @return
	 */
	public static String getContent(String url){
		HttpClient client=new DefaultHttpClient();
		HttpEntity httpEntity=null;
		String result="";
		try {
			HttpGet post=new HttpGet(url);
			HttpResponse httpResponse = client.execute(post);
		    httpEntity=httpResponse.getEntity();
			if(httpEntity!=null){
				result=EntityUtils.toString(httpEntity, "UTF-8").trim();
				return result; 
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				httpEntity.consumeContent();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章