sudha
sudha

Reputation: 11

How to call CQ author URL from a standalone code

I am trying to hit URL in cq Author instance from my standalone code. The URL looks like — http://<somehost>:<someport>//libs/dam/gui/content/reports/export.json

Below is the code:

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()));

But I got a 401 error, which is expected, as I'm not passing any authentication information — hence Sling says:

getAnonymousResolver: Anonymous access not allowed by configuration - requesting credentials.

How can I get resolve this?

Upvotes: 0

Views: 792

Answers (1)

Tomek Rękawek
Tomek Rękawek

Reputation: 9304

You may use Basic HTTP authentication. Adding it to the HttpURLConnection is little awkward:

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

Consider using 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();

Upvotes: 2

Related Questions