Why 403 application-only authentication (post request in java)?


#1

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;

import javax.net.ssl.HttpsURLConnection;

import org.springframework.security.crypto.codec.Base64;

class Test
{
public static void main(String args[]) throws IOException{

		URL url = new URL("https://api.twitter.com/oauth2/token");
		HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
	
		String key = "xxx";
		String secret = "xxx";
		
		String urlEncodedKey = URLEncoder.encode(key,"UTF-8");
		String urlEncodedSecret = URLEncoder.encode(secret,"UTF-8");
		
		String authorizationStringTobeEncoded = urlEncodedKey + ":" + urlEncodedSecret;
		
		String encodedAuthorization=new String (Base64.encode(authorizationStringTobeEncoded.getBytes()));
		
		connection.addRequestProperty("Authorization", "Basic "+encodedAuthorization);
		connection.addRequestProperty("grant_type","client_credentials");
		connection.addRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
		
		connection.setRequestMethod("POST");
		
		int responseCode = connection.getResponseCode();
		
		System.out.println("responseCode  : "+responseCode );
}

}