. Я экспериментирую с API-интерфейсом Twitter с использованием Java. Я пытаюсь получить доступ к API, используя проверку подлинности только с использованием протокола twitter. Twitter Application-only authenticationAPI Twitter для получения твитов, использующих только приложение. Аутентификация возвращает код состояния HTTP. 401.
Вот мой код. Я также попытался НЕ Base64 кодирование в access_token в suggested in this question
public class TwitterAppOnlyAuthenticationClass {
private static final String consumerKey = "My Consumer Key";
private static final String consumerSecret = "My Consumer Secret";
private static OAuthAccessToken getAccessToken() throws UnsupportedEncodingException, IOException {
// Encode Consumer Key and Secret
String encodedConsumerKeyandToken = null;
encodedConsumerKeyandToken = Base64.getEncoder().encodeToString(
(URLEncoder.encode(consumerKey, "UTF-8") + ":" +
URLEncoder.encode(consumerSecret, "UTF-8")).getBytes());
//Get the bearer token
String urlString = "https://api.twitter.com/oauth2/token";
String httpMethod = "POST";
OAuthAccessToken oaat = null;
URL url;
url = new URL (urlString);
HttpsURLConnection u = (HttpsURLConnection)url.openConnection();
u.setDoOutput(true);
u.setRequestMethod(httpMethod);
u.setRequestProperty("Authorization", "Basic " + encodedConsumerKeyandToken);
u.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
OutputStream dos = u.getOutputStream();
dos.write("grant_type=client_credentials".getBytes());
dos.flush();
dos.close();
u.connect();
JsonObject jO = (JsonObject)((Json.createReader(u.getInputStream())).read());
System.out.println(jO.toString());
oaat = new OAuthAccessToken();
oaat.setTokenType(jO.getString("token_type"));
oaat.setAccessToken(jO.getString("access_token"));
return oaat;
}
public static void main(String[] args) {
//Basic Java program to retrieve a collection of the most recent Tweets posted by the user
try {
OAuthAccessToken oaat = getAccessToken();
System.out.println("Access Token : " + oaat.getAccessToken());
//Make the call to {GET statuses/user_timeline}
String urlString = "https://api.twitter.com/1.1/statuses/user_timeline.json?count=100&screen_name=twitterapi";
String httpMethod = "GET";
URL url;
url = new URL (urlString);
HttpsURLConnection u = (HttpsURLConnection)url.openConnection();
u.setDoOutput(true);
u.setRequestMethod(httpMethod);
u.setRequestProperty("Authorization", "Bearer " + oaat);
u.connect();
JsonObject jO = (JsonObject)((Json.createReader(u.getInputStream())).read());
System.out.println(jO.toString());
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(-1);
}
}
}