Java Reference
In-Depth Information
SSLSocketFactory sf =
(SSLSocketFactory)SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket)sf.createSocket(
AUTH_URL, HTTPS_PORT);
String[] suites = socket.getSupportedCipherSuites();
socket.setEnabledCipherSuites(suites);
//allows encrypted connection
return socket;
}
//Convenience to build and encode key/values used in headers
private static String q(String key, String value) throws Exception {
return key + "=" + URLEncoder.encode(value, "UTF-8");
}
}
This code listing is long, but the entire client is contained in this single class, and each part
of it is fairly straightforward. First, create a few constants for your Google account username
and password, as well as the base URL to interact with the API. The main method creates
an instance of the class, and then invokes the getAuthToken method, which creates a secure
connection to Google using the getSecureSocket method. There is nothing specific to REST
at this point, and you can use this method any time you want to obtain an HTTPS connection.
The getAuthToken method is specific to the Google API, requiring you to indicate your user-
name and password, and then use the HTTP POST method to write the data to Google, which
will respond with a security token that you can use for the rest of your session to interact with
the API. In this way, you don't have to re-authenticate on every invocation. The token looks
something like this:
SID=DQAAAH0AAAA3FKWU...-AtltIlsfPdU62RP0B31cqnRzErHL9ppsg
LSID=DQAAAH8AAAAffNC...-E_kPEN76bcZewVajOu3s6zjVlmPa0qUzyuzRUaw
Auth=DQAAAH8AAAAffNC...-AYIySHu9BMnDrJ4UDZA3Jrb1n4mCaoBg
You are only interested in the Auth token here, so substring this response to extract only that
part, and then save it in an instance variable.
Once you have the token, invoke the addPortfolio method, which is where the real inter-
action with the API begins. Create a new connection using your finance URL constant, and
then use a string formatter (added in Java 5) on ATOM_PORTFOLIO_ADD_XML to insert the name
of the portfolio you want to create into the Atom XML boilerplate. This text represents an
Atom <entry> , which you post to the URL. Then immediately read the HTTP response off
the socket, which consists of an Atom <entry> element indicating that you have successfully
added the portfolio: the response contains a RESTful URI representing your new portfolio on
the Web.
Search WWH ::




Custom Search