`
lbyzx123
  • 浏览: 468065 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

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

    博客分类:
  • J2EE
 
阅读更多

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

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

}

分享到:
评论
1 楼 kid_ren 2012-12-05  
很有用,学习了

相关推荐

Global site tag (gtag.js) - Google Analytics