这个问题可能有点天真...
我编写了一个小型 Java 程序,应该查询 CouchDB 实例。但是,CouchDB 不断返回我的用户未获得授权。使用与curl 相同的URL 可以工作。
Java 代码:
HttpGet request = new HttpGet("http://admin:PASSWORD@localhost:5984/ecm_ng_nonpart/_security");
request.addHeader("accept", "application/xml");
try {
System.out.println("Executing request " + request.getMethod() + " " + request.getUri());
ClassicHttpResponse resp = httpClient.execute(request);
BufferedReader br = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
回复:
{"error":"unauthorized","reason":"You are not authorized to access this db."}
卷曲输出:
C:\Users\joche>curl -X GET http://admin:PASSWORD@localhost:5984/ecm_ng_nonpart/_security
{"members":{"roles":["_admin"],"names":["ecmnp","admin"]},"admins":{"roles":["_admin"],"names":["admin"]}}
知道我做错了什么吗?
使用与curl相同的URL可以工作。
您发布的信息不支持此说法。这两种情况下您的 URL 是不同的。
Java:_会话
HttpGet request = new HttpGet("http://admin:PASSWORD@localhost:5984/ecm_ng_nonpart/_sessions");
卷曲:_安全。
curl -X GET http://admin:PASSWORD@localhost:5984/ecm_ng_nonpart/_security
我也遇到了同样的问题。
curl
自动添加 Authorization
标头,其中包含用户名和密码,如 base64
添加在网址 (http://admin:PASSWORD@...
) 中。
我在java中手动添加:
//...
String auth = couchUsername + ":" + couchPassword;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes());
String authHeader = "Basic " + new String(encodedAuth);
var url = couchUrl+":"+couchPort+"/"+couchDatabase+"/"+event.getUuid();
HttpPut httpPut = new HttpPut(url);
httpPut.setEntity(new StringEntity(body));
httpPut.setHeader("Content-Type", "application/json");
httpPut.setHeader("Authorization", authHeader);
CloseableHttpResponse responseCouch = client.execute(httpPut);
//...