package com.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class JsonClientActivity extends Activity {
/** Called when the activity is first created. */
private Button update;
private ListView listView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
update = (Button) findViewById(R.id.update);
listView = (ListView) findViewById(R.id.list);
update.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String urlStr="http://192.168.0.9:8000/TestServer/getjson.action";
String result = GsonUtil.getJson(urlStr);
List<Music> list = GsonUtil.getListFromJson(result);
List<Map<String,Object>> data = getAdapterData(list);
SimpleAdapter adapter =new SimpleAdapter(JsonClientActivity.this, data, R.layout.list, new String[]{"name","author","time"}, new int[]{R.id.name,R.id.author,R.id.time});
listView.setAdapter(adapter);
//listView.
}
});
}
private List<Map<String,Object>> getAdapterData(List list){
List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
for(int i=0;i<list.size();i++){
Map<String,Object> map = new HashMap<String, Object>();
Music music= (Music)list.get(i);
map.put("name",music.getName());
map.put("author", music.getAuthor());
map.put("time",music.getTime());
data.add(map);
}
return data;
}
}
----------------------------------------------------------------------------------------------------------------------------------------------
package com.test;
import java.net.URI;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import com.google.gson.Gson;
public class GsonUtil {
public static String getJson(String url){
HttpClient client = new DefaultHttpClient();
HttpPost request;
try {
request = new HttpPost(new URI(url));
HttpResponse response = client.execute(request);
// 判断请求是否成功
if (response.getStatusLine().getStatusCode() == 200) { //200表示请求成功
HttpEntity entity = response.getEntity();
if(entity!=null){
String beanListToJson = EntityUtils.toString(entity,"GBK");
return beanListToJson;
}
}
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
public static List<Music> getListFromJson(String json){
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<Music>>() {
}.getType();
Gson gson = new Gson();
List<Music> list = gson.fromJson(json.toString(), type);
return list;
}
}
最后记得在manifest配置文件中添加uses-permission android:name="android.permission.INTERNET"