HttpURLConnection 传递参数和隐藏流

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

	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();
		}

 

 

你可能感兴趣的:(工作)