文章來自: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 轉載請保留原文地址