How to call /bin/querybuilder.json in java CQ5 - java

How to call querybuilder API in Java. I have tried this but i am getting no result. But when i am trying to hit in browser with this URL localhost path then the response is coming properly.
URL url = new URL("http://localhost:4502/bin/querybuilder.json?path=/content");
HttpURLConnection servletConnection = (HttpURLConnection) url.openConnection();
servletConnection.setRequestMethod("GET");
servletConnection.setDoOutput(true);
InputStream response = servletConnection.getInputStream();

Based on the code shown, most likely you don't have a session established with your localhost. When you hit that URL in a new browser window you will get redirected to a login page where you must first login with appropriate credentials before you can see the page. But when you make the same request via Java code, you haven't provided any credentials. So you won't be able to get to the content.
Check our Preemptive Basic Auth with HttpUrlConnection? for info on how to provide credentials.

Related

Not able to do a post request to an authenticated Hyperledger Composer rest server in Java

I am not able to do a POST request to the Composer rest server that is authenticated.
I have been trying out Hyperledger composer rest server with
authentication and multiuser enabled.
I have enabled Github based authentication by exporting
COMPOSER_PROVIDERS variable and multiuser mode with Wallet and
identities .
I authenticate the rest server in github and i am able to do rest
operations in the Composer Swagger explorer .
I am also able to do the rest operations in Postman by passing the
url with the access_token .
http://localhost:4200/api/Trader?access_token=xxxxxxxxxxx .This works
in Postman as well.
Problem is i am not able to do a post request to the composer-rest URL from java code even after passing the access token as param. I have tried with OKHttpClient,Apache HTTPClient, java.net client , CloseableHTTPClient .
All it gives me is
Server returned HTTP response code: 401
In all methods i get an "AUTHORIZATION FAILURE" error .
I dont know if i am missing anything , because i am able to do a rest operation from Postman . I take the code format from Postman itself and paste it in the Java code and it still doesnt work . I dont know what i am doing wrong ,
Suggestions , code snippets ?
THANKS !
since you managed to get this running from Postman then you're obviously missing something in your java code.
You probably have the URL correct, but might be missing a header, or a json type or something of the sorts.
Inspect your Postman request and replicate it exactly in your java code, everything, not just the URL.
Keep a log of your request and compare it against the Postman one, to see exactly what the difference is.
Try this code to retrieve cookies:
public void getCookieUsingCookieHandler() {
try {
// Instantiate CookieManager;
// make sure to set CookiePolicy
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
// get content from URLConnection;
// cookies are set by web site
URL url = new URL("http://host.example.com");
URLConnection connection = url.openConnection();
connection.getContent();
// get cookies from underlying
// CookieStore
CookieStore cookieJar = manager.getCookieStore();
List <HttpCookie> cookies =
cookieJar.getCookies();
for (HttpCookie cookie : cookies) {
if (cookie.getName().equalsIgnoreCase("access_token")) {
System.out.println("CookieHandler retrieved cookie: " + cookie.getValue());
break;
}
}
} catch(Exception e) {
System.out.println("Unable to get cookie using CookieHandler");
e.printStackTrace();
}
}
You can refer it from here: https://docs.oracle.com/javase/tutorial/deployment/doingMoreWithRIA/accessingCookies.html

How do I find where an HttpURLConnection is trying to redirect me to?

I have an HttpURLConnection that I do not what to follow redirects, however if a redirect appears I want to know where I would get redirected to. There doesn't seem to be a method of HttpURLConnection that will show me that, is there any way I can get that information?
Get the Header "Location", it contains the URL where you are redirected. Look at the HTTP spec for all the details
First turn of redirect follows:
conn.setInstanceFollowRedirects(false);
conn being your HTTPConnection variable. Then read the Location header.

How to authorize to HTTP server using java

What I do manually:
I open the URL: http://localhost:8080/webadmin/index.html enter login and password.
And click button wich is really do http get request: http://localhost:8080/rest/platform/domain/list
What I do in java:
String addr = "http://localhost:8080/rest/platform/domain/list?_dc=1325843792402"; //"http://localhost:8080/webadmin/index.html";
URL url = new URL(addr);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setUseCaches(false);
httpCon.setAllowUserInteraction(false);
httpCon.setRequestMethod("GET");
OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
out.close();
And get response: 401 Unauthorized.
Understandable why: I should create an authorised connection by entering a login and a password. But how I can do this?
On authentication using form fields in a web page, what happens is the following:
You access a login page. The server marks your session using one of the following methods:
Session cookie, present in the HTTP Response headers. You should store this cookie and resend it afterwards.
Redirect to a new URL in which the session is marked (http://localhost:8080/?sessionKey=3292n9fafjwagwao2903j2fswioanw)
(sometimes) hidden HTML form or Javascript variable which contains the session key and which is POST'ed on every click of a link.
Let us suppose the server uses cookies. You then do a POST request containing:
The cookie you received.
Your username and password in the POST data
The server now marks your session as "logged in" and may even give you a new or extra session identifier.
You then access a secured resource, providing a session identifier proving you are logged in.
You can follow this process very nicely using the Google Chrome Developer Network view (press CTRL+SHIFT+J, go to Network.
How do you translate this to Java code?
Do initial request to login page. Recover session cookie from HTTP headers.
Do a POST to the login form destination. Include the session cookie in the HTTP request header and the username/password in the POST data. Recover the session cookie from HTTP headers.
Now access the protected resource. Include the session cookies in the HTTP request header.
Of course, there are other ways of authenticating users at the webserver level (HTTP BASIC authentication, NTLM...), as explained by other answers here. The above method only works for HTML FORM-based authentication (as used by Facebook, Dropbox, ... and almost all major websites out there)
That depends on the authentication scheme. There are several possibilities, including
Basic access authentication
Digest access authentication
NTLM
Microsoft's HTTP Negotiate/SPNEGO
The server will tell you the correct scheme in its 401 answer. Look for the WWW-Authenticate HTTP header in the answer.
For doing HTTP authentication in Java, see this tutorial which contains a lot of useful information.

How to execute HTTP GET method with cookie value filled?

My problem is that I want to use Java to implement an application which sends an HTTP GET request to some website. However, the target website needs one cookie to be set:
Country=US
If this cookie is null it returns bad indications. My question is how I can set the cookie value before I use openConnection()?
You can use URLConnection and add a Cookie header:
http://www.hccp.org/java-net-cookie-how-to.html
URL myUrl = new URL("http://www.yourserver.com/path");
URLConnection urlConn = myUrl.openConnection();
urlConn.setRequestProperty("Cookie", "Country=US");
urlConn.connect();
You can place the cookie your self by adding a header, or use a higher level HTTP library like Apache's HttpClient which API includes cookies handling features.

Acegi throws AuthenticationCredentialsNotFoundException when opening URl with BrowserLauncher 2

We have a JSF web application that uses Acegi security. We also have a standalone Java Swing application. One function of the Swing app is to load the user's home page in a browser window.
To do this we're currently using Commons HttpClient to authenticate the user with the web app:
String url = "http://someUrl/j_acegi_security_check";
HttpClient client = new HttpClient();
System.setProperty(trustStoreType, "Windows-ROOT");
PostMethod method = new PostMethod(url);
method.addParameter("j_username", "USERNAME");
method.addParameter("j_password", "PASSWORD");
int statusCode = client.executeMethod(method);
if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY ) {
Header locationHeader= method.getResponseHeader("Location");
String redirectUrl = locationHeader.getValue();
BrowserLauncher launcher = new BrowserLauncher();
launcher.openURLinBrowser(redirectUrl);
}
This returns a HTTP 302 redirect response, from which we take the redirect url and open it using BrowserLauncher 2. The url contains the new session ID, something like:
http://someUrl/HomePage.jsf;jsessionid=C4FB2F643CE48AC2DE4A8A4C354033D4
The problem we're seeing is that Acegi processes the redirect but throws an AuthenticationCredentialsNotFoundException. It seems that for some reason the authenticated credentials cannot be found in the security context.
Does anyone have an idea as to why this is happening? If anyone needs more info then I'll be happy to oblige.
Many thanks,
Richard
I have never done Acegi/SpringSecurity, but the symptoms are clear enough: some important information is missing in the request. You at least need to investigate all the response headers if there isn't something new which needs to be passed back in the header of the subsequent request. Maybe another cookie entry which represents the Acegi credentials.
But another caveat is that you in fact cannot open just the URL in a local browser instance, because there's no way to pass the necessary request headers along it. You'll need to have your Swing application act as a builtin webbrowser. E.g. get HTML response in an InputStream and render/display it somehow in a Swing frame. I would check if there isn't already an existing API for that, because it would involve much more work than you'd initially think .. (understatement).
In this case you can do Basic Authentication and set this header in every request instead of sending the jsessionid:
AUTHORIZATION:Basic VVNFUk5BTUU6UEFTU1dPUkQ=
The token VVNFUk5BTUU6UEFTU1dPUkQ= is the username and the password encoded base64.
Example:
scott:tiger
is:
c2NvdHQ6dGlnZXI=
One more thing: use SSL.

Categories