android上客户端到服务端通过Entity传送数据
来源:互联网 发布:gba模拟器mac 编辑:程序博客网 时间:2024/05/22 03:32
传送Json需要各种包,见前面一篇博文。有详细说json的引包问题。
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读取。
代码:
String result=null;HttpClient client = new DefaultHttpClient();HttpResponse response;byte[] data;try { response = client.execute(new HttpGet("http://192.168.56.1:8080/Service/servlet/EntityService")); if(response.getStatusLine().getStatusCode()==200){ data=EntityUtils.toByteArray(response.getEntity()) ; result=new String(data); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block 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 blocke.printStackTrace();} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.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();}
0 0
- android上客户端到服务端通过Entity传送数据
- 客户端通过Http传输数据到服务端
- c语言实现socket服务端/客户端通过tcp传送文件
- 通过Android 客户端上传数据到服务器
- 通过Android 客户端上传数据到服务器
- 通过Android 客户端上传数据到服务器
- 通过Android 客户端上传数据到服务器
- android客户端通过json连接servlet服务端
- Flask之处理客户端通过POST方法传送的数据
- Flask-处理客户端通过POST方法传送的数据
- [Android]Http通信,HttpService服务端通过getEntity获取HttpClient客户端Post上来的数据
- 通过sqoop增量传送oracle数据到hive
- GUI界面,客户端向服务端传送文件
- STM32F107VC+DHT11+ESP8266传送温湿度数据到Yeelink平台上
- Android 手机间的文件传送(socket手机做服务端和客户端进行)
- Android 通过intent跳转页面并传送数据
- Android(客户端)通过socket与QT(服务端)通信
- 2BizBoxERP客户端到服务端的数据访问过程
- python科学计算
- sublime + ctags
- 将网卡名eno16777736改为eth0
- 获取文件当前目录方法
- LevelDB场景分析1--整体结构分析
- android上客户端到服务端通过Entity传送数据
- Opencv之Mat操作(重要)
- 一个策划总监的自白:到底什么是策划?
- Makefile语法分析
- 进程和线程的区别和联系
- windows常用系统库
- CWnd与HWND的区别与转换
- HDU--2024
- leetcode | 3Sum Closest