首页 > Web开发 > 详细

HttpUrlConnection访问Servlet进行数据传输

时间:2015-08-26 17:47:11      阅读:234      评论:0      收藏:0      [点我收藏+]

建立一个URL url = new URL("location");

建立 httpurlconnection :HttpUrlConnection httpConn = (HttpUrlConnection)url.openConnection();//强制类型转换

String requestString = "什么gui";
设置连接属性:
httpConn.setDoOutPut(true); //使用URL进行输出
httpConn.setDoInPut(true); //使用URL进行输入
httpConn.setUseCaches(false); //忽略使用缓存
httpConn.setRequestMethod("Post"); //默认情况是Get方法

设置请求属性:
byte[] requestStringBytes = requestString.getBytes("UTF-8");
httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length);
httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
httpConn.setRequestProperty("Charset", "UTF-8");

建立输出流,写入数据:
httpConn.connect();
DataOutputStream outputStream = new DataOutputStream(httpConn.getOutputStream());
String content = "name="+ URLEncoder.encode(requestString,"utf-8");
outputStream.writeBytes(content);
outputStream.flush();
outputStream.close();

那么在Servlet端 获取数据的方式,
String name = request.getParameter("name"); //这样就能获取到requestString 的字符串

HttpUrlConnection访问Servlet进行数据传输

原文:http://www.cnblogs.com/FakerWang/p/faker.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!