我们经常用json来从服务端返回数据给客户端,我写了一个很简单的demo
服务端:
public class JsonAction extends HttpServlet {
JsonService jsonService;
/**
* Constructor of the object.
*/
public JsonAction() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String msg = JsonTools.createJsonString("person", jsonService.getPerson());
out.println(msg);
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
jsonService = new JsonService();
}
}
public class JsonService {
public Person getPerson(){
Person person = new Person(1001, "jack", "beijing");
return person;
}
public List<Person> getListPersons(){
List<Person> list = new ArrayList<Person>();
Person person1 = new Person(1002, "mark", "shanghai");
Person person2 = new Person(1003, "tony", "guangzhou");
Person person3 = new Person(1004, "rose", "shenzheng");
list.add(person1);
list.add(person2);
list.add(person3);
return list;
}
public List<String> getListString(){
List<String> list = new ArrayList<String>();
list.add("shanghai");
list.add("beijing");
list.add("guangzhou");
return list;
}
public List<Map<String, String>> getMaps(){
List<Map<String, String>> list = new ArrayList<Map<String,String>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("name", "zhangsan");
map1.put("address", "beijing");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("name", "lisi");
map2.put("address", "shansghai");
Map<String, String> map3 = new HashMap<String, String>();
map3.put("name", "wangwu");
map3.put("address", "guangzhou");
list.add(map1);
list.add(map2);
list.add(map3);
return list;
}
}
客户端的代码:
public class MainActivity extends Activity {
Button button;
EditText editText;
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
String str = (String)msg.obj;
Person person=null;
try {
person=JsonTools.getJsonPerson(str);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
editText.setText(person.getId() + " : " + person.getName() + " : " + person.getAddress());
}
};
private static final String url ="http://192.168.1.102:8080/jsonServerProject/servlet/JsonAction";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button1);
editText = (EditText)findViewById(R.id.edit);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Mythread(url).start();
}
});
}
private class Mythread extends Thread{
private String urls;
public Mythread(String urls){
this.urls = urls;
}
@Override
public void run() {
// TODO Auto-generated method stub
InputStream inputStream = null;
ByteArrayOutputStream outputStream = null;
try {
URL url = new URL(urls);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if(connection.getResponseCode()==200){
inputStream = connection.getInputStream();
}
outputStream = new ByteArrayOutputStream();
int len = 0;
byte[] bytes = new byte[1024];
while((len=inputStream.read(bytes))!=-1){
outputStream.write(bytes, 0, len);
}
byte[] bs = outputStream.toByteArray();
String msg = new String(bs);
Message message = Message.obtain();
message.obj = msg;
handler.sendMessage(message);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@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;
}
}
public class JsonTools {
public static Person getJsonPerson(String json) throws JSONException{
Person person = new Person();
JSONObject jsonObject = new JSONObject(json);
JSONObject personJsonObject = jsonObject.getJSONObject("person");
int id = personJsonObject.getInt("id");
String address = personJsonObject.getString("address");
String name = personJsonObject.getString("name");
person.setId(id);
person.setAddress(address);
person.setName(name);
return person;
}
}
客户端截图: