java使用URL类发送Http请求400错误解决
文章来自:http://www.codeif.com/topic/389 转载请保留原文地址
?
使用java,但不使用HttpClient等第三方jar包的情况下发送http请求,有时直接在域名后带参数发送请求时会发生400错误,大家可以测试下如下代码
URL url = new URL("http://www.codeif.com?a=3");InputStream in = url.openStream();BufferedReader bin = new BufferedReader(new InputStreamReader(in, "utf-8"));String s = null;while((s=bin.readLine()) != null){ System.out.println(s);}bin.close();补充:如果你是代理上网,可以参考:java使用代理发送http请求
上面是不是会报400错误,而如果直接访问,不带参数,如下
URL url = new URL("http://www.codeif.com");则正常返回数据
可是我们访问中需要有参数怎么办呢?
其实解决方案也很简单,在域名后加上/
http://www.codeif.com?a=3
改为
http://www.codeif.com/?a=3
其实之所以我们在浏览器中能够使用http://www.codeif.com?a=3这种形式直接访问,不是说这种方式就是可以访问的,而且浏览器帮你加了/,同样我们的HttpClient包也会帮我们加这个/
这样我们在程序中只需稍微处理下url地址,在后面价格/就可以了
我们写一个函数处理下面的情况
http://www.codeif.com > http://www.codeif.com
http://www.codeif.com?a=1 > http://www.codeif.com/?a=1
http://www.codeif.com/topic/360?a=1 不变
可以看出在//后没有/的时候
没有问号的时候在最后加/
有问号的时候在问号前加/
在使用java发送http请求前,可以使用下面的函数对url进行处理
/** * 对url进行处理,将url域名后补充/ * @param url * @return */private String handleUrl(String url) { String result = url; int beginIndex = result.indexOf("//"); if (beginIndex != -1) { int endIndex = result.indexOf("/", beginIndex + 2); if (endIndex == -1) { int questionIndex = result.indexOf("?"); if(questionIndex==-1){ result += "/"; }else { result = result.replaceFirst("/?[?]", "/?"); } } } return result;}文章来自:http://www.codeif.com/topic/389 转载请保留原文地址