I want to implement application only authentication for twitter in Java, just the way it is descried in this documentation: https://dev.twitter.com/oauth/application-only .
My Java code to obtain the bearer token looks like this:
String consumerKey = URLEncoder.encode(RandomStringUtils.randomAlphabetic(15));
String consumerSecret = URLEncoder.encode(RandomStringUtils.randomAlphabetic(25));
String credentials = consumerKey + ":" + consumerSecret;
String credentialsEncoded = Base64.encodeToString(credentials.getBytes("UTF-8"), Base64.NO_WRAP);
Log.d(DEBUG_TAG, "credentials = " + credentials);
Log.d(DEBUG_TAG, "credentialsEncoded = " + credentialsEncoded);
URL url = new URL("https://api.twitter.com/oauth2/token");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("User-Agent", "My Twitter App v1.0.23");
conn.setRequestProperty("Host", "api.twitter.com");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Authorization", "Basic " + credentialsEncoded);
conn.setRequestProperty("Accept-Encoding", "gzip");
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write("grant_type=client_credentials");
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
Log.d(DEBUG_TAG, "responseCode = " + responseCode);
Log.d(DEBUG_TAG, "conn.getResponseMessage() = " + conn.getResponseMessage());
String line = null;
String response = "";
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} catch (Exception ex) {
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
} finally {
while ((line = br.readLine()) != null) {
//Log.d(DEBUG_TAG, "line = " + URLDecoder.decode(line,"UTF-8"));
response += line;
}
}
Log.d(DEBUG_TAG, "response = " + URLDecoder.decode(response, "UTF-8"));
Unfortunatley the output is always like this:
responseCode = 403
conn.getResponseMessage() = Forbidden
response = ����������������Q�0��{�Y�SC�,l�B�^�����Z��<u&����a��^�G�)3��/---4�-D���IrE�,�����mc�6��Y��������������$�{i������
Is something wrong with my implementation? Did I understand the documentation in a wrong way?