android 学习笔记5——get请求+json解析

get请求与post请求类似,同样使用多线程处理网络连接。json解析方面也很简单,两三行就解决问题了,其中解析的json数据来源是百度地图的web api。

MainActivity.java:

package com.example.json;

import java.io.IOException;

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.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	private String result;
	private static final int MSG_SUCCESS = 0;  
    private static final int MSG_FAILURE = 1;  
    private TextView t;
    private Handler handler = new Handler(){  
        public void handleMessage(Message msg){  
            switch(msg.what){  
            case MSG_SUCCESS:  
                t.setMovementMethod(ScrollingMovementMethod.getInstance());  
                //t.setText(Html.fromHtml(result));
                //t.setText(result);
                try {
					JSONObject jsonObject = new JSONObject(result);
					JSONObject content = new JSONObject(jsonObject.getString("content"));
					t.setText("您ip所属位置:"+content.getString("address"));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                break;  
            case MSG_FAILURE:  
                t.setText("fail");  
                break;  
            }  
        }  
    };  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        t = (TextView)findViewById(R.id.tv);
        Get();
    }
    private void Get(){
    	new Thread(){
    		public void run(){
    			String url = "http://api.map.baidu.com/location/ip?ak=1c8e15c5045d29f1b84987d359a02802&coor=bd09ll";
    			HttpGet httpRequest = new HttpGet(url);
    			HttpClient httpclient = new DefaultHttpClient();
    			try {
					HttpResponse httpResponse = httpclient.execute(httpRequest);
					if(httpResponse.getStatusLine().getStatusCode() == 200){
						result = EntityUtils.toString(httpResponse.getEntity());
						handler.obtainMessage(MSG_SUCCESS).sendToTarget();  
					}
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			
    		}
    	}.start();
    }
}

其余的代码(布局、权限设置)和笔记4中的一样。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值