views:

30

answers:

0

Hello, I am working on a twitter oauth login. However, when I do the request_token, the very first step, the response code always return 401 Unauthorized.

I have searched a lot for a week, but I cannot find the solution, please help.

Here is my connection:

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();

For 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 + "\"";  

Also, I am sure that my signature is right, because I used the parameter of twitter example, I can calculate the same result as its example, so I think 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 the nonce and timestamp should be random and unique. So, my method is like that:

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 somebody help me??? Thank you very much.

P.S:I have also removed my apps, and then create a new one. The result also is the same. Also, the apps is write and read already.

related questions