不需要任何其他包
package com.example.json;
import java.io.IOException;
import org.apache.http.HttpResponse;
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.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button btn1;
private TextView txt1;
private String baseUrl="http://ip:8088/ship/servlet/getposinfo";
private String str="";
private Handler handler=new Handler()
{
@Override
public void handleMessage(Message msg) {
// 返回的字符串 直接是个数组
// [{"devid":"1234567800","latitude":"29.4963","longitude":"116.189","postime":"2014-06-10 12:13:00"},
// {"devid":"1234567832","latitude":"29.4943","longitude":"1161.129","postime":"2014-06-11 12:13:00"}]
try {
JSONArray jsonArray = new JSONArray(String.valueOf(msg.obj));
for (int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject2 = (JSONObject)jsonArray.opt(i);
str=str+"第"+i+"个,devid:"+jsonObject2.getString("devid")+"维度:"+jsonObject2.getString("latitude")+"\n";
txt1.setText(str);
Log.v("zms", str);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1=(Button)findViewById(R.id.button1);
txt1=(TextView)findViewById(R.id.textView1);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.v("zms","begin");
/*从安卓3.0以后,就不允许在主线程中直接访问网络,必须在子线程中访问
访问后要修改主线程的UI,需要使用handler通信*/
accessThread mythred=new accessThread();
mythred.start();
}
});
}
class accessThread extends Thread{
@Override
public void run() {
try{
Log.v("zms","ready");
HttpGet geturl=new HttpGet(baseUrl);
DefaultHttpClient httpclient=new DefaultHttpClient();
HttpResponse response=httpclient.execute(geturl);
Log.v("zms","响应码"+response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode()==200)
{
String returnStr=EntityUtils.toString(response.getEntity(),"utf-8");
Log.v("zms","返回值"+returnStr);
Message age=handler.obtainMessage();
age.obj=returnStr;
age.sendToTarget();
} else
{
Log.v("zms","访问网络返回数据失败,错误码:"+response.getStatusLine().getStatusCode());
}
}
catch(IOException e)
{
e.printStackTrace();
}
super.run();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}