Once you have set up your environment, using the API is pretty straightforward:
The first step is to register an oAuth application with Yahoo. It's free, and they will give you a consumer key and consumer secret.
To interact with the library, you need one of those. You get it by calling:
Api api = ApiFactory.getApiInstance(
"your yahoo consumer key",
"your yahoo consumer secret",
"YOURAPPBASEURL/simpleyqlcallback/",
false, null);
Replace
YOURAPPURL
with your application's base URL (ex.: http://mytomcatserver.com/myjar/). The boolean parameter allows you to choose between JSON (true) or XML (false) for query results.
Users must authorize you to act on their behalf. On an user's first access, redirect him to Yahoo by issuing (under a servlet or JSP):
api.askAuthorization(request, response, "RETURNURL");
After he gets authorized, he will be sent back to the
RETURNURL
(which must be on the domain that you registered your key on). This URL will receive an
authdata
string parameter. Store it on your database alongside your user's data.
QueryResult qr = api.query("SOME YQL", authdata);
Here,
authdata
is the string you stored on the database on the previous step, and
SOME YQL
is the query you want to run (e.g.:
select * from social.profile where guid=me
). The
QueryResult
object's
getText()
method will return the result of the call. There you go - but there is a last catch:
Unfortunately, Yahoo expires the access token (which is part of the
authdata
) every hour. In theory, you don't need to worry about that, because the library will refresh the token and retry the call automatically, but you should store the new token on the database whenever it changes (the
QueryRsult
also contains the new authdata).
So after issuing a query, you should have something along the lines of:
if (!qr.getAuthData().equals(authdata)) {
// replace the authdata on the database with qr.getAuthData()
..
}
The calls above may generate
OAuthException
and
IOException
that should be treated accordingly.
Check the Javadoc for more details on those calls.