Chinaunix首页 | 论坛 | 博客
  • 博客访问: 137175
  • 博文数量: 20
  • 博客积分: 434
  • 博客等级: 下士
  • 技术积分: 249
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-05 15:49
文章分类

全部博文(20)

文章存档

2011年(20)

我的朋友

分类: 嵌入式

2011-11-22 10:56:28

服务端需要加上json.jar包,下载地址:

服务端:

JSONDemoServlet.java

package com.test.Demo;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.me.JSONArray;
import org.json.me.JSONObject;

public class JSONDemoServlet extends HttpServlet {
private static final long serialVersionUID = -7368225680407826408L;
private List<User> list;

/**
* 处理post方式提交的数据
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}

/**
* 处理get方式提交的数据
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/plain");
response.setCharacterEncoding(
"UTF-8");
PrintWriter out
= response.getWriter();

//准备用户数据
prepareData();

//JSON数组
JSONArray array = new JSONArray();

for(User bean:list){
//单个用户JSON对象
JSONObject obj = new JSONObject();
try{

obj.put(
"id", bean.getId());
obj.put(
"name", bean.getName());
obj.put(
"email", bean.getEmail());
obj.put(
"gender", bean.getGender());
}
catch (Exception e) {
// TODO: handle exception
}
array.put(obj);
}
//输出
out.write(array.toString());
out.flush();
out.close();
}


private void prepareData()
{
list
= new ArrayList<User>();
User bean1
= new User();
bean1.setId(
1001);
bean1.setName(
"Tony");
bean1.setEmail(
"tony@toeach.net");
bean1.setGender(
"male");
list.add(bean1);

User bean2
= new User();
bean2.setId(
1002);
bean2.setName(
"Jack");
bean2.setEmail(
"jack@hotmail.com");
bean2.setGender(
"male");
list.add(bean2);

User bean3
= new User();
bean3.setId(
1003);
bean3.setName(
"Marry");
bean3.setEmail(
"marry@163.com");
bean3.setGender(
"female");
list.add(bean3);

User bean4
= new User();
bean4.setId(
1004);
bean4.setName(
"Linda");
bean4.setEmail(
"linda@21cn.com");
bean4.setGender(
"female");
list.add(bean4);
}

}

User.java

package com.test.Demo;

public class User {
private int id;

private String name;

private String email;

private String gender;

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

web.xml中配置映射路径:

xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns
=""
xmlns:xsi
=""
xsi:schemaLocation
="
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<servlet>
<servlet-name>JSONDemoServletservlet-name>
<servlet-class>com.test.Demo.JSONDemoServletservlet-class>
servlet>

<servlet-mapping>
<servlet-name>JSONDemoServletservlet-name>
<url-pattern>/JSONDemoServleturl-pattern>
servlet-mapping>


<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>

web-app>

客户端:

package com.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

try {
StringBuffer sb
= new StringBuffer();
// 在测试过程中,经常是用本机做测试服务器,访问本机的IP地址要设置为10.0.2.2
String url = "";
String body
= getContent(url);
JSONArray array
= new JSONArray(body);
for (int i = 0; i < array.length(); i++) {
JSONObject obj
= array.getJSONObject(i);
sb.append(
"id:").append(obj.getInt("id")).append("\t");
sb.append(
"name:").append(obj.getString("name")).append("\r\n");
sb.append(
"gender:").append(obj.getString("gender")).append(
"\t");
sb.append(
"email:").append(obj.getString("email")).append(
"\r\n");
sb.append(
"----------------------\r\n");
}
TextView textView
= (TextView) findViewById(R.id.textView);
textView.setText(sb.toString());
}
catch (Exception e) {
// TODO: handle exception
}

}

private String getContent(String url) throws Exception {
StringBuilder sb
= new StringBuilder();
HttpClient client
= new DefaultHttpClient();
HttpParams httpParams
= client.getParams();

// 设置网络超时参数
HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
HttpConnectionParams.setSoTimeout(httpParams,
5000);
HttpResponse response
= client.execute(new HttpGet(url));
HttpEntity entity
= response.getEntity();
if (entity != null) {
BufferedReader reader
= new BufferedReader(new InputStreamReader(
entity.getContent(),
"UTF-8"), 8192);
String line
= null;
while ((line = reader.readLine()) != null) {
sb.append(line
+ "\n");
}
reader.close();
}

return sb.toString();
}

}

阅读(6093) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~