2012-07-31 40 views
4

我有這樣HttpURLConnection類與參數

http://somecompany.com/restws/ebi/SVI/4048/?Name=Tra&Brand=Software: WebSphere - Open App Servers 

我傳遞一個URL看起來它不喜歡的第二個參數(品牌)。從瀏覽器上面這個查詢字符串工作正常,但只要我在Java中執行,它失敗。當我改變了網絡服務來接受一個單一的參數,那麼這個URL工作正常

http://somecompany.com/restws/ebi/SVI/4048/?Name=Tra 

看來Java是具有第二個參數的問題。我試過了逃生角色和其他所有我能想到的東西,但似乎沒有任何工作。請幫忙!

String uri = "somecompany.com/restws/ebi/SVI/4048/?Name=" 
      + name+ "&Brand=Software: WebSphere - Open App Servers"; 

URL url; 

try { 
    url = new URL(uri); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
    connection.setRequestMethod("GET"); 
    connection.setRequestProperty("Accept", "application/xml"); 
} 
... 
+0

我希望它的錯字,但在你的代碼中,我不相信你應該有字符串uri包含「websphere-open app servers」如果它不是錯字,希望它很容易修復 – GK1667 2012-07-31 14:25:11

回答

6

嘗試URL編碼您的參數。

事情是這樣的:

String uri = "somecompany.com/restws/ebi/SVI/4048/?Name=" +name+ "&Brand="; 
uri = URLEncoder.encode("Software: WebSphere - Open App Servers", "utf-8"); 
+1

這是definitiely要走的路。這就是我修改它的方法,現在一切都可以運行。 String query = String.format(「Name =%s&Brand =%s」,URLEncoder.encode(param1,charset),URLEncoder.encode(param2,charset)); \t \t \t \t \t \t \t嘗試{ \t \t \t \t URL =新的URL(URI +查詢); – Bryan 2012-07-31 18:50:24

+0

已確認。此解決方案有效。 但是安全問題呢?將敏感數據放入網址時可能會泄漏(我正在使用https)? – 2015-06-09 09:59:24

+1

如果你使用https,你的參數被加密。 @DinhNhat – 2015-06-09 11:16:22

2

我也許使用能夠正確處理HTTP參數,並提供合適的編碼等見HttpComponentsthe tutorial更多信息庫。

+0

使用庫是個好主意。你可以試試[DavidWebb](http://hgoebl.github.io/DavidWebb/)。它非常輕巧。 – hgoebl 2014-01-02 11:26:58