服务器端与客户端使用Json进行数据交互

服务器端:

引入相应的包:json-lib-2.2-jdk15.jar

Action:

public String findAll() throws IOException{

List news = newsService.findAll();

//把java 对象列表转换为json对象数组,并转为字符串

JSONArray array = JSONArray.fromObject(news);

//将数据输送到后台,设置数据编码格式和防止后台自动缓存

this.getResponse().setContentType("text/html; charset=utf-8");
this.getResponse().setHeader("Cache-Control", "no-cache");
this.getResponse().getWriter().print(array);
return null;
}

客户端:

public class HttpUtil {
// 通过指定的网络地址获得图片
public static Bitmap getBitmapFromUrl(String bmpUrl) {
URL url;
try {
url = new URL(bmpUrl);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
// 将与指定地址建立的输入流转成图片
Bitmap bmp = BitmapFactory.decodeStream(is);
return bmp;
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

// 从指定服务器地址获得返回的Json数据,并转成字符串
public static String getStringFromUrl(String url) {
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
// 向指定服务器地址发出get请求
try {
HttpResponse response = client.execute(httpGet);
String result = EntityUtils.toString(response.getEntity());
return result;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}


public class NewsService {
private final String baseUrl = "http://169.254.44.91:8080/News";
// 将服务器返回的Json数据,转成List对象
public List getNewsInfo() {
String result = HttpUtil.getStringFromUrl(baseUrl + "/newsAction!findAll.action");
Log.i("result", result);
List meal = new Gson().fromJson(result,new TypeToken>() {}.getType());
Log.i("标题:", meal.get(0).getTitle());
for (News meals : meal) {
meals.setImage("http://169.254.44.91:8080/News/images/"+ meals.getImage());
}
return meal;
}
}

你可能感兴趣的:(代码)