2013-05-15 63 views
0

我把HTTP PUT代碼幾乎逐字從this example from stackoverflow - 我試圖一個XML文件放到一個ExistDB其餘的接口,但我收不到的URLConnection getResponseCode「400錯誤的請求」值()並且完全看不到遠程服務器記錄的任何內容,就好像該請求從未發送過一樣。Java的HttpURLConnection的HTTP PUT錯誤400

URL target = new URL("http://domain.com:8080/exist/rest/db/collection/doc.xml") 
HttpURLConnection uc = (HttpURLConnection) target.openConnection(); 
uc.setDoOutput(true); 
uc.setDoInput(true); 
uc.setRequestMethod("PUT"); 

uc.setConnectTimeout(CONNECT_TIMEOUT); // timeouts are both 2000L 
uc.setReadTimeout(READ_TIMEOUT); //ms 
uc.setRequestProperty("Content-type", "text/xml"); 

// basic Auth s.getLogin() already recorded as username:pwd format 
String auth = new String(Base64.encodeBase64String(s.getLogin().getBytes())); 
auth = auth.replaceAll("\n",""); // sun bug_id 6459815 
uc.setRequestProperty("Authorization", "Basic " + auth); 

uc.connect(); // tried moving this to after the body section below 

PrintWriter body = new PrintWriter(uc.getOutputStream()); 
InputStream sml = smlStream(this.pathid); 
StringBuilder xml = new StringBuilder(new Scanner(sml).useDelimiter("\\A").next()); 
body.print(xml); 
body.close(); 
uc.disconnect(); // appears to make no difference 

uc.getResponseCode()現在有400

值。如果我用在身體上相同的URL和相同的XML文件捲曲(捲曲-v -u UNAME:PW -T文件。 xml http://domain.com:8080/exist/rest/db/collection/doc.xml)發送請求相同用戶標識從相同機器,文檔通過並返回201響應如預期。另一方面,Java版本(使用openjdk7)什麼都不做。

我是否按照正確的順序設置了這些電話?有什麼方法可以獲得有關爲什麼請求語法無效的更多信息?

+0

原來這可能有點誤導性的問題:如果我註釋掉設置基本身份驗證的代碼塊,代碼就可以工作(或者至少會發布到服務器,儘管它會得到401錯誤,但是在所以我的問題被修改:*我的基本身份驗證代碼有什麼問題?* – MrG

回答

0

似乎是最後的線索導致雖然沒有解釋一個解決方案:我替換到sun.misc.BASE64Encoder相當於呼叫並神奇地按預期工作

BASE64Encoder codex = new BASE64Encoder(); 
String auth = codex.encode(s.getLogin().getBytes()); 
uc.setRequestProperty("Authorization", "Basic " + auth); 
的代碼中調用了apache的Base64編碼器

一切都很好。 org.apache.commons.codec.binary.Base64顯然已經壞了。