Advertisement
Guest User

Untitled

a guest
Jan 13th, 2013
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.57 KB | None | 0 0
  1. public void testUserTimelineWithAuthSample() throws Exception {
  2. //This will read the timeline of your account.
  3. String method = "GET";
  4. String url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
  5.  
  6. String oAuthConsumerKey = "Your value here.";
  7. String oAuthConsumerSecret = "Your value here."; //<--- DO NOT SHARE THIS VALUE
  8.  
  9. String oAuthAccessToken = "Your value here.";
  10. String oAuthAccessTokenSecret = "Your value here."; //<--- DO NOT SHARE THIS VALUE
  11.  
  12. String oAuthNonce = String.valueOf(System.currentTimeMillis());
  13. String oAuthSignatureMethod = "HMAC-SHA1";
  14. String oAuthTimestamp = time();
  15. String oAuthVersion = "1.0";
  16.  
  17. String signatureBaseString1 = method;
  18. String signatureBaseString2 = url;
  19. String signatureBaseString3Templ = "oauth_consumer_key=%s&oauth_nonce=%s&oauth_signature_method=%s&oauth_timestamp=%s&oauth_token=%s&oauth_version=%s";
  20. String signatureBaseString3 = String.format(signatureBaseString3Templ,
  21. oAuthConsumerKey,
  22. oAuthNonce,
  23. oAuthSignatureMethod,
  24. oAuthTimestamp,
  25. oAuthAccessToken,
  26. oAuthVersion);
  27.  
  28. String signatureBaseStringTemplate = "%s&%s&%s";
  29. String signatureBaseString = String.format(signatureBaseStringTemplate,
  30. URLEncoder.encode(signatureBaseString1, "UTF-8"),
  31. URLEncoder.encode(signatureBaseString2, "UTF-8"),
  32. URLEncoder.encode(signatureBaseString3, "UTF-8"));
  33.  
  34. System.out.println("signatureBaseString: "+signatureBaseString);
  35.  
  36. String compositeKey = URLEncoder.encode(oAuthConsumerSecret, "UTF-8") + "&" + URLEncoder.encode(oAuthAccessTokenSecret, "UTF-8");
  37.  
  38. String oAuthSignature = computeSignature(signatureBaseString, compositeKey);
  39. System.out.println("oAuthSignature : "+oAuthSignature);
  40.  
  41. String oAuthSignatureEncoded = URLEncoder.encode(oAuthSignature, "UTF-8");
  42. System.out.println("oAuthSignatureEncoded: "+oAuthSignatureEncoded);
  43.  
  44. String authorizationHeaderValueTempl = "OAuth oauth_consumer_key="%s", oauth_nonce="%s", oauth_signature="%s", oauth_signature_method="%s", oauth_timestamp="%s", oauth_token="%s", oauth_version="%s"";
  45.  
  46. String authorizationHeaderValue = String.format(authorizationHeaderValueTempl,
  47. oAuthConsumerKey,
  48. oAuthNonce,
  49. oAuthSignatureEncoded,
  50. oAuthSignatureMethod,
  51. oAuthTimestamp,
  52. oAuthAccessToken,
  53. oAuthVersion);
  54. System.out.println("authorizationHeaderValue: "+authorizationHeaderValue);
  55.  
  56.  
  57. System.out.println("url: "+url);
  58. System.out.println("authorizationHeaderValue:"+authorizationHeaderValue);
  59.  
  60. GetMethod getMethod = new GetMethod(url);
  61. getMethod.addRequestHeader("Authorization", authorizationHeaderValue);
  62. HttpClient cli = new HttpClient();
  63. int status = cli.executeMethod(getMethod);
  64. System.out.println("Status:"+status);
  65.  
  66. long responseContentLength = getMethod.getResponseContentLength();
  67. System.out.println("responseContentLength:"+responseContentLength);
  68.  
  69. String response = getMethod.getResponseBodyAsString();
  70. System.out.println("response: "+response);
  71. }
  72.  
  73.  
  74. private static String computeSignature(String baseString, String keyString) throws GeneralSecurityException, UnsupportedEncodingException, Exception
  75. {
  76. SecretKey secretKey = null;
  77.  
  78. byte[] keyBytes = keyString.getBytes();
  79. secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");
  80.  
  81. Mac mac = Mac.getInstance("HmacSHA1");
  82.  
  83. mac.init(secretKey);
  84.  
  85. byte[] text = baseString.getBytes();
  86.  
  87. return new String(Base64.encodeBase64(mac.doFinal(text))).trim();
  88. }
  89.  
  90. private String time() {
  91. long millis = System.currentTimeMillis();
  92. long secs = millis / 1000;
  93. return String.valueOf( secs );
  94. }
  95.  
  96. String url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2";
  97.  
  98. public String generateNonce() {
  99. Random gen = new Random(System.currentTimeMillis());
  100. StringBuilder nonceBuilder = new StringBuilder("");
  101. String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  102. int baseLength = base.length();
  103.  
  104. // Taking random word characters
  105. for (int i = 0; i < 32; ++i) {
  106. int position = gen.nextInt(baseLength);
  107. nonceBuilder.append(base.charAt(position));
  108. }
  109.  
  110. String nonce = toBase64(nonceBuilder.toString());
  111.  
  112. return nonce;
  113. }
  114.  
  115. // In your code :
  116. String oAuthNonce = generateNonce();
  117.  
  118. public void testUserTimelineWithParams() throws Exception {
  119. //This will read the timeline of the 'twitterapi' account.
  120.  
  121. String method = "GET";
  122. String url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
  123. List<NameValuePair> urlParams = new ArrayList<NameValuePair>();
  124. urlParams.add( new NameValuePair("screen_name","twitterapi") );
  125. urlParams.add( new NameValuePair("count", "10") );
  126.  
  127. String oAuthConsumerKey = "Your value";
  128. String oAuthConsumerSecret = "Your value"; //<--- DO NOT SHARE THIS VALUE
  129.  
  130. String oAuthAccessToken = "Your value";
  131. String oAuthAccessTokenSecret = "Your value"; //<--DO NOT SHARE THIS VALUE
  132.  
  133. String oAuthNonce = String.valueOf(System.currentTimeMillis());
  134. String oAuthSignatureMethod = "HMAC-SHA1";
  135. String oAuthTimestamp = time();
  136. String oAuthVersion = "1.0";
  137.  
  138. String signatureBaseString1 = method;
  139. String signatureBaseString2 = url;
  140.  
  141. List<NameValuePair> allParams = new ArrayList<NameValuePair>();
  142. allParams.add(new NameValuePair("oauth_consumer_key", oAuthConsumerKey));
  143. allParams.add(new NameValuePair("oauth_nonce", oAuthNonce));
  144. allParams.add(new NameValuePair("oauth_signature_method", oAuthSignatureMethod));
  145. allParams.add(new NameValuePair("oauth_timestamp", oAuthTimestamp));
  146. allParams.add(new NameValuePair("oauth_token", oAuthAccessToken));
  147. allParams.add(new NameValuePair("oauth_version", oAuthVersion));
  148. allParams.addAll(urlParams);
  149.  
  150. Collections.sort(allParams, new NvpComparator());
  151.  
  152. StringBuffer signatureBaseString3 = new StringBuffer();
  153. for(int i=0;i<allParams.size();i++)
  154. {
  155. NameValuePair nvp = allParams.get(i);
  156. if (i>0) {
  157. signatureBaseString3.append("&");
  158. }
  159. signatureBaseString3.append(nvp.getName() + "=" + nvp.getValue());
  160. }
  161.  
  162. String signatureBaseStringTemplate = "%s&%s&%s";
  163. String signatureBaseString = String.format(signatureBaseStringTemplate,
  164. URLEncoder.encode(signatureBaseString1, "UTF-8"),
  165. URLEncoder.encode(signatureBaseString2, "UTF-8"),
  166. URLEncoder.encode(signatureBaseString3.toString(), "UTF-8"));
  167.  
  168. System.out.println("signatureBaseString: "+signatureBaseString);
  169.  
  170. String compositeKey = URLEncoder.encode(oAuthConsumerSecret, "UTF-8") + "&" + URLEncoder.encode(oAuthAccessTokenSecret, "UTF-8");
  171.  
  172. String oAuthSignature = computeSignature(signatureBaseString, compositeKey);
  173. System.out.println("oAuthSignature : "+oAuthSignature);
  174.  
  175. String oAuthSignatureEncoded = URLEncoder.encode(oAuthSignature, "UTF-8");
  176. System.out.println("oAuthSignatureEncoded: "+oAuthSignatureEncoded);
  177.  
  178. String authorizationHeaderValueTempl = "OAuth oauth_consumer_key="%s", oauth_nonce="%s", oauth_signature="%s", oauth_signature_method="%s", oauth_timestamp="%s", oauth_token="%s", oauth_version="%s"";
  179.  
  180. String authorizationHeaderValue = String.format(authorizationHeaderValueTempl,
  181. oAuthConsumerKey,
  182. oAuthNonce,
  183. oAuthSignatureEncoded,
  184. oAuthSignatureMethod,
  185. oAuthTimestamp,
  186. oAuthAccessToken,
  187. oAuthVersion);
  188. System.out.println("authorizationHeaderValue: "+authorizationHeaderValue);
  189.  
  190. StringBuffer urlWithParams = new StringBuffer(url);
  191. for(int i=0;i<urlParams.size();i++) {
  192. if(i==0)
  193. {
  194. urlWithParams.append("?");
  195. }
  196. else
  197. {
  198. urlWithParams.append("&");
  199. }
  200. NameValuePair urlParam = urlParams.get(i);
  201. urlWithParams.append(urlParam.getName() + "=" + urlParam.getValue());
  202. }
  203.  
  204. System.out.println("urlWithParams: "+urlWithParams.toString());
  205. System.out.println("authorizationHeaderValue:"+authorizationHeaderValue);
  206.  
  207. GetMethod getMethod = new GetMethod(urlWithParams.toString());
  208. getMethod.addRequestHeader("Authorization", authorizationHeaderValue);
  209.  
  210. HttpClient cli = new HttpClient();
  211. int status = cli.executeMethod(getMethod);
  212. System.out.println("Status:"+status);
  213.  
  214. long responseContentLength = getMethod.getResponseContentLength();
  215. System.out.println("responseContentLength:"+responseContentLength);
  216.  
  217. String response = getMethod.getResponseBodyAsString();
  218. System.out.println("response: "+response);
  219. }
  220.  
  221. private static String computeSignature(String baseString, String keyString) throws GeneralSecurityException, UnsupportedEncodingException, Exception
  222. {
  223. SecretKey secretKey = null;
  224.  
  225. byte[] keyBytes = keyString.getBytes();
  226. secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");
  227.  
  228. Mac mac = Mac.getInstance("HmacSHA1");
  229.  
  230. mac.init(secretKey);
  231.  
  232. byte[] text = baseString.getBytes();
  233.  
  234. return new String(Base64.encodeBase64(mac.doFinal(text))).trim();
  235. }
  236.  
  237. private String time() {
  238. long millis = System.currentTimeMillis();
  239. long secs = millis / 1000;
  240. return String.valueOf( secs );
  241. }
  242.  
  243. public class NvpComparator implements Comparator<NameValuePair> {
  244.  
  245. public int compare(NameValuePair arg0, NameValuePair arg1) {
  246. String name0 = arg0.getName();
  247. String name1 = arg1.getName();
  248. return name0.compareTo(name1);
  249. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement