Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package me.confu5ed.twitchapi;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.URL;
- import java.net.URLEncoder;
- import javax.net.ssl.HttpsURLConnection;
- // Lib: http://commons.apache.org/proper/commons-io/
- import org.apache.commons.io.*;
- // Lib: http://mvnrepository.com/artifact/org.json/json/20141113
- import org.json.*;
- /**
- * Utility Class for Updating Twitch Channel via TwitchAPI.
- * @version 1.0
- * @author Marcel Naeve <[email protected]>
- */
- public final class TwitchChannelUpdate {
- /**
- * APIKey (OAuth2.0 Token) for TwitchAPI: channel_edit scale needed,
- * you can get one for this Application by: <code>serious-pro.de/twitchgametracker/token.html</code>.
- */
- public static String APIKey = "";
- /**
- * Request URL - TwitchAPI should be constant until the API get updated.
- */
- private static String stringUrl = "https://api.twitch.tv/kraken/channels/";
- /**
- * Twitch Channel Name.
- */
- public static String channel = "";
- /**
- * Update Channel Information by TwitchAPI.
- * @param key what will be updated? (game/status/delay)
- * @param data newValue
- * @return boolean update success=>true/failed=>false
- */
- public static boolean update(String key, String data) {
- URL url;
- String response = "";
- try {
- // Prepare
- url = new URL(stringUrl + channel);
- String basicAuth = "OAuth " + APIKey;
- String sendData = "channel[" + URLEncoder.encode(key, "UTF-8") + "]=" + URLEncoder.encode(data, "UTF-8");
- // Create Request
- HttpsURLConnection apiConnection = (HttpsURLConnection) url.openConnection();
- apiConnection.setRequestMethod("PUT");
- apiConnection.setDoOutput(true);
- apiConnection.setRequestProperty("Accept", "application/vnd.twitchtv.v3+json");
- apiConnection.setRequestProperty("X-Requested-With", "TwitchGameTracker");
- apiConnection.setRequestProperty("Authorization", basicAuth);
- // Connect to API and send Data
- apiConnection.connect();
- apiConnection.getOutputStream().write(sendData.getBytes("UTF-8"));
- // Read Response Data
- InputStream inputStream = null;
- System.out.println("ResponseCode: " + apiConnection.getResponseCode());
- if(apiConnection.getResponseCode() == 200)
- {
- inputStream = apiConnection.getInputStream();
- } else {
- inputStream = apiConnection.getErrorStream();
- }
- if(inputStream != null) response = IOUtils.toString(inputStream);
- // Disconnect from API
- apiConnection.disconnect();
- } catch (IOException e) {
- // TODO API Request Failed: Permissions??
- e.printStackTrace();
- return false;
- }
- if(response.startsWith("{")) {
- JSONObject json = new JSONObject(response);
- // TODO check data has been changed and give optical feedback to gui
- System.out.println(json.toString());
- }
- //------------------
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement