我正在使用CouchDB 2.0.0版本。 我正在尝试使用Java代码从API中检索数据。 浏览器中的url工作正常,但不会在eclipse中显示数据。 例如,在使用以下网址时:
http://<ip-address>/_node/couchdb@localhost/_stats
但是这样做会得到以下异常: java.net.SocketException:来自服务器的文件意外结束
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:802)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:663)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:799)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:663)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1335)
答案 0 :(得分:0)
有点晚了。我也遇到过这个问题。服务器实际上响应了一个错误,因为从java调用时,您必须指定授权类型(通常是Basic),以及使用Base64编码的用户信息。它适用于浏览器和curl,因为它们都添加了请求属性。
假设您正在使用:
http://<ip-address>/_node/couchdb@localhost/_stats
您的连接可能配置如下:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(2000); // Two seconds (or any timeout you decide) timeout
// Other user agent can be used. I've also tried curl/7.51.0 as user agent as well
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("Content-type", "application/json");
if (url.getUserInfo() != null && !"".equals(url.getUserInfo())) {
// userInfo MUST be Base64 encoded
connection.setRequestProperty("Authorization", "Basic " + Base64.encodeBase64String(url.getUserInfo().getBytes()));
}
connection.setUseCaches(false);
希望这有帮助。