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协议获取数据就行了,具体代码如下。
服务器端:
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(); }
相关文章推荐
- Android接收/发送jSON数据
- Android基于XMPP Smack Openfire下学习开发IM(四)单人聊天和多人聊天(发送消息、接收消息)
- android发送/接收json数据
- Android—Volley:接收服务端发送的json数据乱码问题解决
- java.net.ProtocolException: Unexpected status line: 关于Java/Android http post json的发送接收
- Android之发送与接收JSON数据
- Android基于XMPP Smack Openfire下学习开发IM(四)单人聊天和多人聊天(发送消息、接收消息)
- Android开发之接收和发送短信
- 简单掌握Android开发中彩信的发送接收及其附件的处理
- Android开发中HTTP协议HttpPost向服务器发送JSon数据格式的数据
- Android基于XMPP Smack Openfire开发IM【三】客户端接收服务器发送的消息
- android发送/接收json数据
- Android基于XMPP Smack Openfire下学习开发IM(四)单人聊天和多人聊天(发送消息、接收消息)
- android发送/接收json数据
- android发送/接收json数据
- Android基于XMPP Smack Openfire下学习开发IM(四)单人聊天和多人聊天(发送消息、接收消息)
- Android基于XMPP Smack Openfire下学习开发IM(四)单人聊天和多人聊天(发送消息、接收消息)
- android开发tcp发送与接收
- Android开发:客户端与服务器通过传递和接收json数据进行交互
- Android开发之与服务器(jsp)发送、接受JSON数据