HttpURLConnection 传递参数和隐藏流

本文介绍了一种在使用HttpURLConnection发送POST请求时遇到的问题及解决方案。当URL中已包含参数时,如何确保额外的POST数据能正确传递。通过设置合适的请求头解决了这一难题。

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

今天改以前的程序,以前的程序如下:

	URL url = new URL(urlString);
	urlConnection = (HttpURLConnection) url.openConnection();

	urlConnection.setRequestMethod(method);
	urlConnection.setDoOutput(true);
	urlConnection.setDoInput(true);
                
	urlConnection.setUseCaches(false);
		if (propertys != null)
			for (String key : propertys.keySet()) {
				urlConnection.addRequestProperty(key, propertys.get(key));
			}

		if (method.equalsIgnoreCase("POST") && parameters != null) {
			// 模拟浏览器发送UTF-8编码的请求
			urlConnection.getOutputStream().write(parameters.getBytes("UTF-8"));
			urlConnection.getOutputStream().flush();
			urlConnection.getOutputStream().close();
		}

 这种情况下urlString是一个不含有参数的地址,比如“http://localhost:8080/xrap/servlet”。

情况出现了,我要在url中添加参数,这样在服务端可以用

request.getParameter("cmd");

 取到参数信息,但是当我把urlString变量变成“http://localhost:8080/xrap/servlet?cmd=2&mdn=xinxi”的时候,服务端却怎么也接收不到隐藏流(parameters )里写的东西了。没在url中加参数信息的时候是好用的。

后来将代码改成这样就即可以传参数,又能写隐藏流了:

	URL url = new URL(urlString);
	urlConnection = (HttpURLConnection) url.openConnection();

	urlConnection.setRequestMethod(method);
	urlConnection.setDoOutput(true);
	urlConnection.setDoInput(true);

	//下面两句是新加的
                urlConnection.setRequestProperty("accept", "text/xml;text/html");
                urlConnection.setRequestProperty("Content-Type",
                              "text/xml;charset=utf-8);

		urlConnection.setUseCaches(false);
		if (propertys != null)
			for (String key : propertys.keySet()) {
				urlConnection.addRequestProperty(key, propertys.get(key));
			}

		if (method.equalsIgnoreCase("POST") && parameters != null) {
			// 模拟浏览器发送UTF-8编码的请求
			urlConnection.getOutputStream().write(parameters.getBytes("UTF-8"));
			urlConnection.getOutputStream().flush();
			urlConnection.getOutputStream().close();
		}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值