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中的一样。