码迷,mamicode.com
首页 > Web开发 > 详细

HttpUrlConnection访问Servlet进行数据传输

时间:2015-08-26 17:49:23      阅读:166      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!