首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

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

2012-09-23 
url中的参数含有空格,导致请求失败的问题今天写了个程序,代码如下:public class Test {/*** @param args*/

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

}

热点排行