簡體   English   中英

java httpurlconnection http放錯誤400

[英]java httpurlconnection http put error 400

從stackoverflow的這個示例中幾乎逐字讀取了HTTP PUT代碼-我試圖將XML文件放入ExistDB rest接口中,但是我從URLConnection getResponseCode()接收到“ 400 Bad Request ”值,卻看不到任何記錄通過遠程服務器,就好像從未發送過請求。

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文件使用curl(curl -v -u uname:pw -T file.xml http://domain.com:8080/exist/rest/db/collection/doc.xml )以相同的用戶ID從同一台計算機發送請求,文檔將按照預期進行處理並返回201響應。 另一方面,Java版本(使用openjdk7)不執行任何操作。

這些接聽電話的順序正確嗎? 有什么方法可以獲取有關為什么請求語法無效的更多信息?

似乎最后一條線索導致了解決方案,盡管沒有解釋:我將對Apache Base64編碼器的調用替換為對sun.misc.BASE64Encoder的等效調用,並且該代碼神奇地按預期工作了

BASE64Encoder codex = new BASE64Encoder();
String auth = codex.encode( s.getLogin().getBytes() );
uc.setRequestProperty("Authorization", "Basic " + auth ); 

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM