de.clemensbartz.jtwitchstreamsapi.util.network.JSONRequestor.java Source code

Java tutorial

Introduction

Here is the source code for de.clemensbartz.jtwitchstreamsapi.util.network.JSONRequestor.java

Source

/*
 * Copyright 2014 Clemens Bartz
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package de.clemensbartz.jtwitchstreamsapi.util.network;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

/**
 * Created by clemens on 22.11.14.
 */
public class JSONRequestor {
    public static String clientId = "";

    public synchronized static String getContent(URL url) throws IOException {
        HttpURLConnection connection = null;
        connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("GET");
        connection.setInstanceFollowRedirects(false);
        connection.addRequestProperty("Accept", "application/vnd.twitchtv.v2+json");
        if (clientId != null && clientId.length() > 0) {
            connection.addRequestProperty("Client-ID", clientId);
        }
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException(
                    "Response code was not as expected: " + Integer.toString(connection.getResponseCode())
                            + " with message: " + connection.getResponseMessage());
        }
        InputStream inputStream = connection.getInputStream();
        // Converter InputString to String from here: http://stackoverflow.com/a/5445161/1447767
        Scanner s = new Scanner(inputStream).useDelimiter("\\A");
        String content = s.hasNext() ? s.next() : "";
        if (content.equals("")) {
            throw new IOException("Received empty response from server.");
        }
        inputStream.close();
        connection.disconnect();
        return content;
    }

    public synchronized static <T> T requestJSON(URL url, Class<T> clazz) throws IOException {
        return new Gson().fromJson(JSONRequestor.getContent(url), clazz);
    }

    public synchronized static <T> T requestJSONForTypeToken(URL url, TypeToken<T> clazz) throws IOException {
        return new Gson().fromJson(JSONRequestor.getContent(url), clazz.getType());
    }
}