Generating OAuth Token
Generating OAuth Token
http://code.google.com/p/qfacebookconnect/issues/detail?id=6
1) Send a post request to http://twitter.com/oauth/request_token 2) Set the request Authorization header with the AuthorizeTokenString. You need to set this header for every request [POST or GET]. 3) Set the request Content-Type header with the application/x-www-form-urlencoded. You need to set this header for every request [POST or GET] You can generate AuthorizeTokenString with the help of following code.
// call to method 1 //request method (POST, GET) // url you want to hit // parameters if available otherwise pass array of parameters of size 0 // token if available otherwise pass null
params = new PostParameter[0]; } // vector containing the header parameter Vector oauthHeaderParams = new Vector(); // CONSUMER_KEY consumer key of your application registered with Twitter oauthHeaderParams.addElement(new PostParameter("oauth_consumer_key", CONSUMER_KEY)); oauthHeaderParams.addElement(new PostParameter("oauth_signature_method", "HMAC-SHA1")); oauthHeaderParams.addElement(new PostParameter("oauth_timestamp", timestamp)); oauthHeaderParams.addElement(new PostParameter("oauth_nonce", nonce)); oauthHeaderParams.addElement(new PostParameter("oauth_version", "1.0")); if (null != otoken) { oauthHeaderParams.addElement(new PostParameter("oauth_token", otoken.getToken())); } Vector signatureBaseParams = new Vector();
//call to method 3. This method will add all the entries of second vector to 1st one.
addAll(signatureBaseParams, oauthHeaderParams); ########################################################### # // method 3 # private void addAll(Vector to, Vector from){ # for(int i=0; i<from.size(); i++) # to.addElement(from.elementAt(i)); # } ###########################################################
//call to method 4. This method will add all the pasing parameters to the passing vector addAllParam(signatureBaseParams, params); ########################################################### # // method 4 # private void addAllParam(Vector to, PostParameter[] params) { # for(int i=0; i<params.length; i++) # to.addElement(params[i]); # }
########################################################### //call to method 5. This will parse all the querystring parameters from the url and add them to the passing vector parseGetParameters(url, signatureBaseParams);
StringBuffer base = new StringBuffer(method); base.append("&"); //call 1st method 6 and then 7. base.append(encode(constructRequestURL(url))); base.append("&"); // call method 8 1st and then 7. base.append(encode(normalizeRequestParameters(signatureBaseParams))); String oauthBaseString = base.toString(); // call to method 9. String signature = generateSignature(oauthBaseString, otoken); oauthHeaderParams.addElement(new PostParameter("oauth_signature", signature)); //call to method 10. return "OAuth " + encodeParameters(oauthHeaderParams, ",", true); }
// method 5. private void parseGetParameters(String url, Vector signatureBaseParams) { int queryStart = url.indexOf("?"); if (-1 != queryStart) { //tokenizing the string with the & String[] queryStrs = StringUtil.split(url.substring(queryStart + 1), "&"); for (int i=0; i<queryStrs.length; i++) { //tokenizing the string with the = String[] split = StringUtil.split(queryStrs[i], "="); if (split.length == 2) { //adding the parameters to vector after decoding. signatureBaseParams.addElement( new PostParameter(URLDecoder.decode(split[0]), URLDecoder.decode(split[1]
// method 6. public String constructRequestURL(String url) { int index = url.indexOf("?"); if (-1 != index) { url = url.substring(0, index); } int slashIndex = url.indexOf("/", 8); String baseURL = url.substring(0, slashIndex).toLowerCase(); int colonIndex = baseURL.indexOf(":", 8); if (-1 != colonIndex) { // url contains port number if (baseURL.startsWith("http://") && baseURL.endsWith(":80")) { // http default port 80 MUST be excluded baseURL = baseURL.substring(0, colonIndex); } else if (baseURL.startsWith("https://") && baseURL.endsWith(":443")) { // http default port 443 MUST be excluded baseURL = baseURL.substring(0, colonIndex); } } url = baseURL + url.substring(slashIndex); return url; }
// method 7. public String encode(String value) { String encoded = null; try { encoded = URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException ignore) { } StringBuffer buf = new StringBuffer(encoded.length());
char focus; for (int i = 0; i < encoded.length(); i++) { focus = encoded.charAt(i); if (focus == '*') { buf.append("%2A"); } else if (focus == '+') { buf.append("%20"); } else if (focus == '%' && (i + 1) < encoded.length() && encoded.charAt(i + 1) == '7' && encoded.charAt(i + 2) == 'E') { buf.append('~'); i += 2; } else { buf.append(focus); } } return buf.toString(); } // method 8. public String normalizeRequestParameters(Vector params) { //call 1st method 8-1 and then 8-2 return encodeParameters(sort(params)); } // method 8-1.sort the passing parameter public final Vector sort(Vector params){ Vector v=new Vector(); Enumeration e = params.elements(); while (e.hasMoreElements()) { PostParameter param =(PostParameter)e.nextElement(); int i=0; for (i=0; i<v.size(); i++) { int c=param.getName().compareTo(((PostParameter)v.elementAt(i)).getName()); if (c<0) { // s should go before i v.insertElementAt(param, i); break; } else if (c==0) { // s already there break; } } if (i>=v.size()) { // add s at end v.addElement(param); } } return v; } //Method 8-2. public String encodeParameters(Vector postParams) {
return encodeParameters(postParams, "&", false); } // method 9. private String generateSignature(String data, OAuthToken token) { byte[] mac = null; try { String oauthSignature = ""; if (null == token) { //consumer key of your registered application oauthSignature = encode(CONSUMER_SECRET) + "&"; } else {
//this code will generate hmac-sha1 based signature. //use your api accordingly to generate this signature
HMAC m=new HMAC(new HMACKey(oauthSignature.getBytes()),new SHA1Digest()); byte[] bytes=data.getBytes("UTF-8"); m.update(bytes, 0, bytes.length); mac = new byte[m.getLength()]; m.getMAC(mac, 0); }catch (CryptoTokenException cte) { // should never happen } catch (CryptoUnsupportedOperationException cuoe) { // should never happen }catch(Exception e){} return new Base64().encode(mac); } -----------------------------------------------------
4) Encode the passing parameters and then write to stream. //call to method 11 query = encodeParameters(parameters) 5) Set the header for content length and set it with query.lenght(). You need to set this header for every request [POST or GET] 6) You will get the similar response after sending request to http://twitter.com/oauth/request_token
oauth_token=94tgf5JeAF5aCSqzSFZQrzJON2DXPIXKlxkkOiRcQA&oauth_toke n_secret=9sAHn709oIuBNgu9FbLAqiPXPmAVyvPSsYkm7jGYsM&oauth_callbac k_confirmed=true 7) Initialize OAuthToken after extracting oauth_token and oauth_token_secret from the above response 8) Send a GET Request to http://twitter.com/oauth/authorize?oauth_token=" + oToken.getToken() and this will return you html based response 9) Take parameter array of size 4 10) Extract the required data from response
PostParameter [] params = new PostParameter[4]; params[0] = new PostParameter("authenticity_token" //call to method 12. Response is html string which we get by calling above url. , catchPattern(response, "\"authenticity_token\" type=\"hidden\" value=\"", "\" />")); params[1] = new PostParameter("oauth_token", catchPattern(response,"name=\"oauth_token\" type=\"hidden\" value=\"","\" />")); params[2] = new PostParameter("session[username_or_email]", username); params[3] = new PostParameter("session[password]", password);
11) Get the authorize url from the response String authorizeURL = catchPattern(response, "<form action=\"","\" id=\"login_form\""); // method 12
private String catchPattern(String body, String before, String after){ int beforeIndex = body.indexOf(before); int afterIndex = body.indexOf(after, beforeIndex); return body.substring(beforeIndex + before.length(), afterIndex); }
12) Extract the cookie from the response header and set it to the header of authorizeURL request 13) Send a POST Request to extracted authorizeURL with above parameters. This will return you html based response. 14) Extract the pin with the help of following code from the response
pin = catchPattern(response, "<div id=\"oauth_pin\">\n ","\n</div>"); 15) Send a POST request to http://twitter.com/oauth/access_token with the following parameter new PostParameter[]{new PostParameter("oauth_verifier", pin)} 16) The above request will return you a response like
oauth_token=94tgf5JeAF5aCSqzSFZQrzJON2DXPIXKlxkkOiRcQA&oauth_toke n_secret=9sAHn709oIuBNgu9FbLAqiPXPmAVyvPSsYkm7jGYsM 17) Initialize OAuthToken with above response. This is your required token and persist this token. You need to send this token with every request [timeline, tweeting etc]