401 error while accessing request_token - made an an attempt to implement OAuth for twitter in Java


#1

made an an attempt to implement OAuth for twitter in Java. Dont know the reason, but my code doesn’t work, IOException is thrown with the reason “java.io.IOException: Server returned HTTP response code: 401”.

code attached here.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import sun.misc.BASE64Encoder;

public class Request {
    
   
    
    public static String read(String url) {
        StringBuffer buffer = new StringBuffer();
        try {
        
            long oauth_timestamp = (System.currentTimeMillis()/1000);
            
             String[][] data = {
                //{"oauth_callback", "http://localhost:9081/abc"},
                {"oauth_consumer_key", "mykey"},
                {"oauth_nonce",  String.valueOf(oauth_timestamp)},
                {"oauth_signature", "mysignature"},
                {"oauth_signature_method", "HMAC-SHA1"},
                {"oauth_timestamp", String.valueOf(oauth_timestamp)},
                {"oauth_version", "1.0"}
            };

            /**
             * Generation of the signature base string
             */
            String signature_base_string = 
                "POST&"+URLEncoder.encode(url, "UTF-8")+"&";
            for(int i = 0; i < data.length; i++) {
                // ignore the empty oauth_signature field
                if(i != 2) {
                signature_base_string +=
                    //URLEncoder.encode(data[i][0], "UTF-8") + "%3D"+
                    URLEncoder.encode(data[i][1], "UTF-8") + "%26";
                }
            }
            // cut the last appended %26 
            signature_base_string = signature_base_string.substring(0,
                signature_base_string.length()-3);

            /**
             * Sign the request
             */
            Mac m = Mac.getInstance("HmacSHA1");
            m.init(new SecretKeySpec("CONSUMER_SECRET".getBytes(), "HmacSHA1"));
            m.update(signature_base_string.getBytes());
            byte[] res = m.doFinal();
            String sig = String.valueOf(new BASE64Encoder().encode(res));
            data[3][1] = sig;

           /**
            * Create the header for the request
            */
           String header = "OAuth ";
           for(String[] item : data) {
                header += item[0]+"=\""+item[1]+"\", ";
           }
           // 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);

           
           TrustManager[] trust = new TrustManager[]{
			new X509TrustManager(){
				
				public java.security.cert.X509Certificate[] getAcceptedIssuers(){
					return null;
				}
				public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType){
					
				}
				public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType){
					
				}
			}
		};
	
			
			try{
				SSLContext  context = SSLContext.getInstance("SSL");
				context.init(null, trust, new java.security.SecureRandom());
				HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
				
			} catch (Exception e) {
				// TODO: handle exception
			}
           
           
           
           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);
           connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0");

           OutputStream output = connection.getOutputStream();
           output.write(header.getBytes(charset));

           BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

           String read;
           while((read = reader.readLine()) != null) {
               buffer.append(read);
           }
        }
        catch(Exception e) {
            e.printStackTrace();
        }

       return buffer.toString();
   }

   public static void main(String[] args) {
       System.out.println(Request.read("https://api.twitter.com/oauth/request_token"));
   }
}

#2

Me too facing same problem… please help anyone.