Exception is java.net.UnknownHostException: www.api.twitter.com


#1

I am trying to read profile information of an twitter user withe the follwoing code

		 public String getUrl(){
		        
		        String method = "GET";

		        String url = "https://api.twitter.com/1.1/users/lookup.json";
		        List<NameValuePair> urlParams = new ArrayList<NameValuePair>();
		        String screen_name="MyTailor";
		        urlParams.add( new NameValuePair("screen_name",screen_name));
		        String oAuthConsumerKey = "********";
		        String oAuthConsumerSecret = "**************"; //<--- DO NOT SHARE THIS VALUE

		        String oAuthAccessToken = "**********";/*"142334403-cw1jFc112rXzqWt3xwXr6LEDA8PxAIe9F4RSoOTR";*/
		        String oAuthAccessTokenSecret = "***********"; //<--DO NOT SHARE THIS VALUE

		        String oAuthNonce = String.valueOf(System.currentTimeMillis());
		        String oAuthSignatureMethod = "HMAC-SHA1";
		        String oAuthTimestamp =time();
		        String oAuthVersion = "1.0";

		        String signatureBaseString1 = method;
		        String signatureBaseString2 = url;

		        List<NameValuePair> allParams = new ArrayList<NameValuePair>();
		        allParams.add(new NameValuePair("oauth_consumer_key", oAuthConsumerKey));
		        allParams.add(new NameValuePair("oauth_nonce", oAuthNonce));
		        allParams.add(new NameValuePair("oauth_signature_method", oAuthSignatureMethod));
		        allParams.add(new NameValuePair("oauth_timestamp", oAuthTimestamp));
		        allParams.add(new NameValuePair("oauth_token", oAuthAccessToken));
		        allParams.add(new NameValuePair("oauth_version", oAuthVersion));
		        allParams.addAll(urlParams);

		        
//		        
		        Collections.sort(allParams,new Comparator<NameValuePair>(){
		                               public int compare(NameValuePair arg0, NameValuePair arg1) {
		        String name0 = arg0.getName();
		        String name1 = arg1.getName();
		        return name0.compareTo(name1);
		    }
		                           });

		        StringBuffer signatureBaseString3 = new StringBuffer();
		        for(int i=0;i<allParams.size();i++)
		        {
		            NameValuePair nvp = allParams.get(i);
		            if (i>0) {
		                signatureBaseString3.append("&");
		            }
		            signatureBaseString3.append(nvp.getName() + "=" + nvp.getValue());
		        }

		        String signatureBaseStringTemplate = "%s&%s&%s";
		        
		        String signatureBaseString = null; 
		            try {
		                signatureBaseString = String.format(signatureBaseStringTemplate, 
		                                                                    URLEncoder.encode(signatureBaseString1, "UTF-8"), 
		                                                                    URLEncoder.encode(signatureBaseString2, "UTF-8"),
		                                                                    URLEncoder.encode(signatureBaseString3.toString(), "UTF-8"));
		            } catch (UnsupportedEncodingException ex) {
		                /*Logger.getLogger(TwitterOath.class.getName()).log(Level.SEVERE, null, ex);*/
		            }

		        System.out.println("signatureBaseString: "+signatureBaseString);

		        String compositeKey = null;
		            try {
		                compositeKey = URLEncoder.encode(oAuthConsumerSecret, "UTF-8") + "&" + URLEncoder.encode(oAuthAccessTokenSecret, "UTF-8");
		            } catch (UnsupportedEncodingException ex) {
		            }

		        String oAuthSignature = null;
		            try {
		                oAuthSignature = computeSignature(signatureBaseString, compositeKey);
		            } catch (GeneralSecurityException ex) {

		            } catch (UnsupportedEncodingException ex) {

		            } catch (Exception ex) {

		            }  
		            System.out.println("oAuthSignature       : "+oAuthSignature);

		        String oAuthSignatureEncoded = null;
		            try {
		                oAuthSignatureEncoded = URLEncoder.encode(oAuthSignature, "UTF-8");
		            } catch (UnsupportedEncodingException ex) {
		            }

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

		        String authorizationHeaderValue = String.format(authorizationHeaderValueTempl,
		                                                            oAuthConsumerKey,
		                                                            oAuthNonce,
		                                                            oAuthSignatureEncoded,
		                                                            oAuthSignatureMethod,
		                                                            oAuthTimestamp,
		                                                            oAuthAccessToken,
		                                                            oAuthVersion);


		        StringBuffer urlWithParams = new StringBuffer(url);
		        for(int i=0;i<urlParams.size();i++) {
		            if(i==0) 
		            {
		                urlWithParams.append("?");
		            }
		            else
		            {
		                urlWithParams.append("&");
		            }
		            NameValuePair urlParam = urlParams.get(i);
		            urlWithParams.append(urlParam.getName() + "=" + urlParam.getValue());
		        }

		        System.out.println("urlWithParams: "+urlWithParams.toString());
		        System.out.println("authorizationHeaderValue:"+authorizationHeaderValue);
		        String[] code=new String[2];
		        code[0]=urlWithParams.toString();
		        code[1]=authorizationHeaderValue;
		        String finalUrl=urlWithParams.toString().concat(authorizationHeaderValue);
		        
		            return finalUrl;
		    }
		 
		private String time() {
			 long millis = System.currentTimeMillis();
			 long secs = millis / 1000;
			 return String.valueOf( secs );
			 }

	 
		 private static String computeSignature(String baseString, String keyString) throws GeneralSecurityException, UnsupportedEncodingException, Exception 
		 {
		 SecretKey secretKey = null;

		 byte[] keyBytes = keyString.getBytes();
		 secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");

		 Mac mac = Mac.getInstance("HmacSHA1");

		 mac.init(secretKey);

		 byte[] text = baseString.getBytes();

		 return new String(Base64.encodeBase64(mac.doFinal(text))).trim();
		 }

the result:

signatureBaseString: GET&https%3A%2F%2Fapi.twitter.com%2F1.1%2Fusers%2Flookup.json&oauth_consumer_key%3DEm8ihpf165mbFA8UBFJIHJUDs%26oauth_nonce%3D1424778603136%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1424778603%26oauth_token%3D142334403-cw1jFc112rXzqWt3xwXr6LEDA8PxAIe9F4RSoOTR%26oauth_version%3D1.0%26screen_name%3DMyTailor
oAuthSignature       : mnL3xgLXA4krYVNn13V8+vIlv4A=
urlWithParams: https://api.twitter.com/1.1/users/lookup.json?screen_name=MyTailor
authorizationHeaderValue:OAuth oauth_consumer_key="EXXXXXXXXXXXXUDs", oauth_nonce="1424778603136", oauth_signature="mnL3xgLXA4krYVNn13V8%2BvIlv4A%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1424778603", oauth_token="142334403-cw1jFc112rXzqWt3xwXr6LEDA8PxAIe9F4RSoOTR", oauth_version="1.0"

Exception
java.net.UnknownHostException: www.api.twitter.com

Response:
{"errors":[{"code":215,"message":"Bad Authentication data."}]}

Help me, thanks in advance


#2

I cannot see anywhere in your code where you explicitly try to call www.api.twitter.com but that is indeed not a valid hostname and it isn’t surprising you’re hitting an UnknownHostException.

Is there any reason for you not to use a library like Twitter4J to do this?