编辑: 好的,我发现这绝对是身份验证问题: 这个简短的Python脚本可以很好地完成任务:
import requests
from requests.auth import HTTPBasicAuth
URL = "https://wiki.myCompany.corp/confluence-dev/rest/api/content/180158489";
r = requests.get(URL, auth = HTTPBasicAuth('myUser', 'myPass'), verify=False)
r.raise_for_status()
print(r.json())
为什么它不能与Java一起使用?
初始问题:
我正在尝试使用Apache httpclient / httpcore编写一个简单的Http请求以获取Confluence页面的内容,但是我得到的只是状态404。
这是我的代码:
String url = "https://wiki.mycompany.corp/confluence-dev/rest/api/content/180158489";
HttpHost proxy = new HttpHost("proxy.myCompany.at", 57165);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("myUsername", "myPassword");
provider.setCredentials(AuthScope.ANY, credentials);
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultCredentialsProvider(provider);
builder.setRoutePlanner(routePlanner);
HttpClient client = builder.build();
HttpGet get = new HttpGet(url);
HttpResponse r = client.execute(get);
System.out.println(r.getStatusLine().toString());
输出: 找不到HTTP / 1.1 404
在浏览器中打开该URL时,只要登录即可获得正确的融合JSON。当我注销并尝试在浏览器中打开该URL时,我将获得JSON
{
"statusCode":404,
"data":
{
"authorized":false,
"valid":true,
"allowedInReadOnlyMode":true,
"errors":[],"successful":false
},
"message":"No content found with id: ContentId{id=180158489}",
"reason":"Not Found"
}
对我来说,这看起来有点像我的代码中的身份验证无法正常工作。
您有什么主意吗?
答案 0 :(得分:0)
好的,我找到了解决方案(以某种方式)。 在我的Java代码中,身份验证不起作用(出于各种原因,我在多个示例中都看到过身份验证如此……)。
无论如何, 不过有效的是,如果我手动设置标题,例如:
HttpGet request = new HttpGet(url);
String authorizationString = "Basic " + Base64.getEncoder().encodeToString(("myUser:myPass").getBytes()).replace("\n", "");
request.setHeader(HttpHeaders.AUTHORIZATION, authorizationString);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
System.out.println(response.getStatusLine().toString());
结果:
HTTP / 1.1 200确定