利用get和post的传参(客户端)

<span style="font-size:14px; font-family: Arial, Helvetica, sans-serif;">1、链接服务</span>
<span style="font-size:14px;"><span style="white-space:pre">			</span>URL url = new URL(httpUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setConnectTimeout(10000);//设置连接超时时间
			con.setRequestMethod("GET"); //设置请求方法  此处需大写  此时为get传参,当进行post传参时应改为post
			con.setReadTimeout(10000); //设置读取超时时间
			con.connect();//连接网络</span>

2、从客户端传递数据进入服务端()

get传参: (此段代码应放在链接服务前)

servlet端调用doget()加入resp.setContentType("text/html;charset=UTF-8");//解决中文乱码问题

<span style="font-size:14px;"><span style="white-space:pre">			</span>String encoder = URLEncoder.encode("张三", "UTF-8");  //解决中文乱码问题
			httpUrl  = httpUrl +"?name="+encoder+"&password=123";          </span>

post传参:(此处不能用下面方式转换代码)(servlet中调用dopost方法)

servlet端调用dopost()加入req.setCharacterEncoding("UTF-8");     //此段代码只有在dopost中才有作用

resp.setContentType("text/html;charset=UTF-8");   //防止中文输出乱码问题

<span style="font-size:14px;"><span style="white-space:pre">			</span>
			OutputStream os = con.getOutputStream();
			PrintWriter writer = new PrintWriter(os);
			writer.print("name=张三&password=123");         //不用转换
			writer.flush();</span>

3、读取链接成功后从服务端读取的数据

<span style="font-size:14px;"><span style="white-space:pre">			</span>InputStream is = con.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));    
			
			StringBuilder builder = new StringBuilder();
			String line=null;
			while ((line = reader.readLine())!= null) {
				builder.append(line);     //将获取的数据存在StringBuffer中
			}</span>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值