I am working on twitter oauth login. However, when I do request_token , the very first step, the response code always returns 401 Unauthorized .
I searched many times a week, but I canโt find a solution, please help.
Here is my link:
URL url = new URL("https://api.twitter.com/oauth/request_token"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestProperty("Host","api.twitter.com"); conn.setRequestProperty("Authorization", data); conn.setRequestMethod("POST"); conn.connect();
According to my data:
String data = "OAuth oauth_nonce=\"" + oauth_nonce + "\", oauth_callback=\"" + oauth_callback + "\", oauth_signature_method=\"" + oauth_signature_method + "\", oauth_timestamp=\"" + oauth_timestamp + "\", oauth_consumer_key=\"" + oauth_consumer_key + "\", oauth_signature=\"" + oauth_signature + "\", oauth_version=\"" + oauth_version + "\"";
In addition, I am sure that my signature is correct, because I used the twitter example parameter, I can calculate the same result as its example, so I believe that my method is right.
Here is my calculation:
String oauth_para = "oauth_callback=" + oauth_callback + "&oauth_consumer_key=" + oauth_consumer_key + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_version=" + oauth_version; String signingRequests = "POST&" + requestToken + "&" + URLEncoder.encode(oauth_para, "UTF-8"); String key = oauth_consumer_secret + "&"; SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1"); Mac mac = null; try { mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); } catch(Exception e) { System.err.println("Error: " + e); } byte[] rawHmac = mac.doFinal(signingRequests.getBytes()); String oauth_signature = Base64.encodeBytes(rawHmac); oauth_signature = URLEncoder.encode(oauth_signature);
I understand that nonce and timestamp must be random and unique. So my method is as follows:
StringBuffer buffer = new StringBuffer("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); StringBuffer sb = new StringBuffer(); Random r = new Random(); int range = buffer.length(); for (int i = 0; i < 43;i ++) { sb.append(buffer.charAt(r.nextInt(range))); } long epoch = System.currentTimeMillis() / 1000; String oauth_nonce = sb.toString();
Can someone help me?
PS: I also uninstalled my applications and then created a new one. The result is also the same. In addition, applications are already writing and reading.