java httpurlconnection http放错误400

时间:2013-05-15 23:42:13

标签: java http httpurlconnection put

我从this example from stackoverflow逐字逐句地接受了HTTP PUT代码 - 我试图将一个XML文件放入ExistDB休息接口,但是我收到了“ 400 Bad Request ”值URLConnection getResponseCode()并且看不到远程服务器记录的任何内容,就好像请求从未发送过一样。

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)在下发送请求来自相同机器的userid,文档将通过并按预期返回201响应。另一方面,Java版本(使用openjdk7)什么都不做。

我是否按正确的顺序进行了这些固定电话会议?有没有办法获得有关请求语法无效的原因的更多信息?

1 个答案:

答案 0 :(得分:0)

似乎最后的线索导致了一个解决方案,虽然没有解释:我用等效的sun.misc.BASE64Encoder调用取代了对apache Base64编码器的调用,代码神奇地按预期工作

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

一切都很好。 org.apache.commons.codec.binary.Base64显然已经坏了。