Can't authenticate with Java's HttpURLConnection?

Basically i’ve been trying to set up a connection to the twitch API, but got caught up at the Authentification process, this is the important part of my java code:

URL url = new URL("https://api.twitch.tv/kraken/users/UsernameThatShouldFollow/follows/channels/channelToFollow");

HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty("Accept", "application/vnd.twitchtv.v3+json");
httpCon.setRequestProperty("Authorization", "OAuth fadfasdasdfasdas");//oauth: in front?
httpCon.setRequestMethod("PUT");
httpCon.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
String line = "";
while((line = in.readLine()) != null)
    System.out.println(line);
in.close();

and this is the error message I get:

java.io.IOException: Server returned HTTP response code: 401 for URL: https://api.twitch.tv/kraken/users/UsernameThatShouldFollow/follows/channels/channelToFollow
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at test.Test.main(Test.java:28)

Anyone got a clue what I’m doing wrong?

You are getting a 401 Unauthorized response meaning that the OAuth token is probably wrong.

HttpURLConnection will throw an IOException if you call getInputStream() when the status response code (getResponseCode()) is not between 200 and 299. If you get a response outside of that range you should be calling getErrorStream() instead. By doing so you should be able to read the error message that twitch responded with.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.