如何从独立代码中调用CQ作者URL

时间:2014-11-07 14:12:39

标签: cq5 aem sling

我试图从我的独立代码中点击cq Author实例中的URL。该网址类似于 - http://<somehost>:<someport>//libs/dam/gui/content/reports/export.json

以下是代码:

URL url = new URL(newPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");
connection.setReadTimeout(15 * 10000);
connection.connect();

reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

但是由于我没有传递任何身份验证信息,我得到了401错误,这是预期的,因此Sling说:

  

getAnonymousResolver:配置不允许匿名访问 - 请求凭据。

我如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您可以使用基本HTTP身份验证。将其添加到HttpURLConnection有点尴尬:

Authenticator.setDefault(new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("admin", "admin".toCharArray());
    }
});

考虑使用Apache HttpClient

UsernamePasswordCredentials creds = new UsernamePasswordCredentials("admin", "admin");
DefaultHttpClient authorizedClient = new DefaultHttpClient();
HttpUriRequest request = new HttpGet(url);
request.addHeader(new BasicScheme().authenticate(creds, request));
HttpResponse response = authorizedClient.execute(request);
InputStream stream = response.getEntity().getContent();