1

I have this cURL request:

curl -H 'Accept: application/vnd.twitchtv.v3+json' -H 'Authorization: OAuth <access_token>' \
-X PUT https://api.twitch.tv/kraken/users/<bot_name>/follows/channels/<channel_name>

I need to turn it into a Java URLConnection request. This is what I have so far:

String url = "https://api.twitch.tv/kraken/?oauth_token=" + bot.botOAuth.substring("oauth:".length());

URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);

conn.setRequestMethod("PUT");

OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write("https://api.twitch.tv/kraken/users/" + bot.botName + "/follows/channels/" + gamrCorpsTextField.getText());
out.close();

new InputStreamReader(conn.getInputStream());

Any help will be appreciated!

blackbishop
  • 30,945
  • 11
  • 55
  • 76
Ion Lee
  • 13
  • 1
  • 4

1 Answers1

1

The URL you are preparing to open in this code:

String url = "https://api.twitch.tv/kraken/?oauth_token=" + bot.botOAuth.substring("oauth:".length());

does not match your curl request URL:

https://api.twitch.tv/kraken/users/<bot_name>/follows/channels/<channel_name>

You appear to want something more like this:

URL requestUrl = new URL("https://api.twitch.tv/kraken/users/" + bot.botName
        + "/follows/channels/" + gamrCorpsTextField.getText());
HttpURLConnection connection = (HttpUrlConnection) requestUrl.openConnection();

connection.setRequestMethod("PUT");
connection.setRequestProperty("Accept", "application/vnd.twitchtv.v3+json");
connection.setRequestProperty("Authorization", "OAuth <access_token>");
connection.setDoInput(true);
connection.setDoOutput(false);

That sets up a "URLConnection request" equivalent to the one the curl command will issue, as requested. From there you get the response code, read response headers and body, and so forth via the connection object.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • Thanks! I added `connection.setRequestProperty("Content-Length", connection.getContentLength()+"");` as well, but now it is throwing a `java.lang.IllegalStateException: Already connected` error. Any idea why? – Ion Lee Apr 25 '15 at 04:15
  • You can no longer set request properties after performing any operation that requires the HTTP request to be sent. One such operation is `getContentLength()`, as that retrieves the length of the *response* content. You should anyway not need to directly set the content length of the *request*. Just use `doOutput(true)`, and write the request body via the connection's `OutputStream`. – John Bollinger Apr 25 '15 at 16:03