1

I am trying to get the request_token to sign in with twitter in an app, but I always get 401 Error. I have created my app in dev.twitter and I have the consumer key, secret and the callback.

This is my method:

def readSomething(String url){
    StringBuffer buffer = new StringBuffer();
    try {
    /** 
     * get the time - note: value below zero 
     * the millisecond value is used for oauth_nonce later on
     */
        int millis = (int) System.currentTimeMillis() * -1;
        int time = (int) millis / 1000;

        /**
         * Listing of all parameters necessary to retrieve a token
         * (sorted lexicographically as demanded)
         */
         def data = [

            "oauth_nonce": String.valueOf(millis),
            "oauth_signature":"",
            "oauth_signature_method":"HMAC-SHA1",
            "oauth_timestamp": String.valueOf(time),
            "oauth_version":"1.0"
         ]

        /**
         * Generation of the signature base string
         */
        String signature_base_string = 
            "POST&"+URLEncoder.encode(url, "UTF-8")+"&";
        data.each{
            // ignore the empty oauth_signature field
            if(it.key != "oauth_signature") {
            signature_base_string +=
                URLEncoder.encode(it.key, "UTF-8") + "%3D" +
                URLEncoder.encode(it.value, "UTF-8") + "%26";
            }
        }
        // cut the last appended %26 
        signature_base_string = signature_base_string.substring(0,
            signature_base_string.length()-3);

        /**
         * Sign the request
         */
        def signingKey=URLEncoder.encode(CONSUMER_SECRET, "UTF-8")+"&"
        Mac m = Mac.getInstance("HmacSHA1");
        m.init(new SecretKeySpec(signingKey.getBytes(), "HmacSHA1"));
        m.update(signature_base_string.getBytes());
        byte[] res = m.doFinal();
        String sig = String.valueOf(res.encodeBase64());

        data["oauth_signature"] = sig;

       /**
        * Create the header for the request
        */
       String header = "OAuth ";
      data.each {
            header += it.key+"=\""+it.value+"\", ";
       }
       // cut off last appended comma
       header = header.substring(0, header.length()-2);

       System.out.println("Signature Base String: "+signature_base_string);
       System.out.println("Authorization Header: "+header);
       System.out.println("Signature: "+sig);

       String charset = "UTF-8";
       URLConnection connection = new URL(url).openConnection();
       connection.setDoInput(true);
       connection.setDoOutput(true);
       connection.setRequestProperty("Accept-Charset", charset);
       connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
       connection.setRequestProperty("Authorization", header);
       OutputStream output = connection.getOutputStream();
       output.write(header.getBytes(charset));

       BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
       println"reader "+reader
       String read;
       while((read = reader.readLine()) != null) {
           buffer.append(read);
       }
    }
    catch(Exception e) { 
        e.printStackTrace();
    }
    println"buffer "+buffer
    println"buffer "+buffer.getClass()
    println"buffer "+buffer.toString()

   return buffer.toString()

}

Is there any wrong with it?

I believe I am not signing correctly and the oauth_signature is wrong. Is there any way to check if this signature is ok?

I try to do this (http://stackoverflow.com/questions/2964392/implement-oauth-in-java) but is still not working, Any others ideas what could be happening?

Thanks in advance

gonzasr
  • 11
  • 1
  • Not tried it, but that's not really very Groovy code... And have you tried using something like HttpBuilder which handles OAuth http://groovy.codehaus.org/modules/http-builder/doc/auth.html rather than trying to hack your own handler together? – tim_yates Nov 07 '12 at 09:42
  • [Here's an example of using Twitter4J](https://gist.github.com/1133768) via Groovy to read the tweets on your timeline – tim_yates Nov 07 '12 at 13:11
  • Hi tim_yates, thanks for the quick answer. Your right, is a mix between java a groovy, cos the code is half-copy from somewhere in java, but I am working with grails, so it doesnt really matters. – gonzasr Nov 08 '12 at 16:06
  • I will try with http-builter and well see. Thanks again – gonzasr Nov 08 '12 at 16:07

0 Answers0