JSON实现Android 网络数据交换(包括复杂对象的传送)

本文详细介绍了如何在服务器端和客户端之间通过HTTP进行JSON数据的交互,包括服务端创建JSON数据并使用HttpservletResponse进行响应,以及客户端如何通过HttpClient执行HTTP GET或POST请求来获取和处理这些数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,服务端到客户端
服务端新建Json数据,HttpservletResponse是请求对象的返回,得到他的writer,把json转换成string就可以。写在doGet里。
代码:

res.setContentType("UTF-8");
PrintWriter pw = res.getWriter();
JSONObject json = new JSONObject();
json.put("name","fwz");
pw.write(json.toString());

客户端,使用HttpClient的execute的方法。用httpGet去执行。返回HttpResponse。再从response读取。
代码:

BufferedReader bufferedReader = null;
StringBuilder sb = new StringBuilder();
String s = "";
try {
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(new HttpGet("http://10.0.2.2:8080/myFirstServlet/JSONServer"));
HttpParams httpParams = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
HttpEntity entity = response.getEntity();
if (entity!=null) {
bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8")); //8192
while((s=bufferedReader.readLine())!=null) {
sb.append(s);
}
}
nameTextView.setText(sb.toString()); //这里输出得到的JSon数据(未解析)
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}


2,客户端到服务器端的传送

客户端,跟前面差不多,也是利用httpClient的execute方法,不过发送数据用Post。结合entity。
代码:

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.0.2.2:8080/myFirstServlet/JSONServer");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", "ze");
StringEntity entity = new StringEntity(jsonObject.toString());
post.setEntity(entity);
HttpResponse responString = client.execute(post);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


服务端,只要写一个读取的方法就可以,在方法里处理HttpservletRequest的数据
代码: 这里只是输出

try {
BufferedInputStream in = new BufferedInputStream(req.getInputStream());
int i;
char c;
while ((i=in.read())!=-1) {
c=(char)i;
System.out.print(c);
}
System.out.println();
System.out.println("test");
}
catch (Exception ex) {
ex.printStackTrace();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值