您的位置:首页 > 移动开发 > Android开发

android 开发:Json的发送和接收

2015-04-03 08:50 288 查看
最近在搞一个android app,使用到和服务器的json交互技术。服务器端我是简单的使用servlet,来接收来自app的请求,处理json使用org.json这个jar包。

服务器端:

1. 将要发送的对象处理成JSONObject 或者 JSONArray对象,这样只要toString就可以变成JSON语句了。

  JSONArray JSONArr = reader.getNewsItemInJson(page);

2.设置响应头的内容类型为:text/json
response.setContentType("text/json;charset=UTF-8");

3.将对象转化成字节数组,写入输出流
response.getOutputStream().write(JSONArr.toString().getBytes());

android app端则使用普通的HTTP协议获取数据就行了,具体代码如下。

  

public static String readJsonString(String urlStr){
StringBuffer sb  = new StringBuffer();
HttpURLConnection conn=null;
try{
URL url = new URL(urlStr);
conn =(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setDoInput(true);
if(conn.getResponseCode()==200){
InputStream is = conn.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len=0;
while(true){
len = is.read(buffer);
if(len==-1){
break;
}else {
outputStream.write(buffer);
}
}
byte[] result = outputStream.toByteArray();
String str = new String(result, 0, result.length, "gbk");
sb.append(str);
outputStream.close();
is.close();
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(conn!=null) {
conn.disconnect();
}
}
return sb.toString();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: