读书人

url中的参数含有空格导致请求失败的

发布时间: 2012-09-23 10:28:11 作者: rapoo

url中的参数含有空格,导致请求失败的问题

今天写了个程序,代码如下:

public class Test {

/**
* @param args
*/
public static void main(String[] args) throws Exception {
String urlStr = "
http://localhost:8080/bhtsys/index.jsp?name=1 中华人民共和国";
URL url = new URL(urlStr);
URLConnection hpCon = url.openConnection();
InputStream in = hpCon.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
}

}

}

?

index.jsp页面如下:

<body bgcolor="red">
中华人民共和国
<%
String name=request.getParameter("name");
name=new String(name.getBytes("iso-8859-1"),"UTF-8");
out.println(name);
%>
</body>

?

一运行报如下错误:

?

?

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 505 for URL: http://localhost:8080/bhtsys/index.jsp?name=1 中华人民共和国
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1313)
at com.bhtec.action.Test.main(Test.java:19)

于是到网上查一下:

原来是参数中有空格导致的,解决方法为:1、用+或者%20代替url参数中的空格。2、或者在提交参数时对url使用js中encodeURIComponent函数。 代码如下:

?

public class Test {

/**
* @param args
*/
public static void main(String[] args) throws Exception {
String urlStr = "
http://localhost:8080/bhtsys/index.jsp?name=1 中华人民共和国";
urlStr=urlStr.replace(" ", "%20");
URL url = new URL(urlStr);
URLConnection hpCon = url.openConnection();
InputStream in = hpCon.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
}

}

读书人网 >编程

热点推荐