Example usage for javax.net.ssl HttpsURLConnection getContentEncoding

List of usage examples for javax.net.ssl HttpsURLConnection getContentEncoding

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection getContentEncoding.

Prototype

public String getContentEncoding() 

Source Link

Document

Returns the value of the content-encoding header field.

Usage

From source file:com.cloudbees.tftwoway.Client.java

public static void main(String[] args) throws Exception {
    URL url = new URL(SERVER_ADDRESS);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

    SSLContext sslContext = createSSLContext();
    connection.setSSLSocketFactory(sslContext.getSocketFactory());

    connection.connect();/*from   w ww. j  a va 2 s .  co m*/

    int responseCode = connection.getResponseCode();
    String response = IOUtils.toString(connection.getInputStream(), connection.getContentEncoding());
    System.out.println(responseCode);
    System.out.println(response);
}

From source file:com.clueride.auth.Auth0ConnectionImpl.java

@Override
public int makeRequest(URL auth0Url, String accessToken) throws IOException {

    /* Open Connection */
    HttpsURLConnection connection = (HttpsURLConnection) auth0Url.openConnection();

    /* Provide 'credentials' */
    connection.setRequestProperty("Authorization", "Bearer " + accessToken);

    /* Retrieve response */
    responseCode = connection.getResponseCode();
    responseMessage = connection.getResponseMessage();
    if (responseCode == 200) {
        InputStream inputStr = connection.getInputStream();
        String encoding = connection.getContentEncoding() == null ? "UTF-8" : connection.getContentEncoding();
        jsonResponse = IOUtils.toString(inputStr, encoding);
        LOGGER.debug(String.format("Raw JSON Response:\n%s", jsonResponse));
    } else {//from w w  w . j av  a2  s  . c o m
        LOGGER.error(String.format("Unable to read response: %d %s", responseCode, responseMessage));
    }
    return responseCode;
}

From source file:com.gmt2001.TwitchAPIv2.java

private JSONObject GetData(request_type type, String url, String post, String oauth) {
    JSONObject j = new JSONObject();

    try {//from ww w. ja v a  2s.  co m
        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.addRequestProperty("Accept", header_accept);

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        }

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(timeout);

        c.connect();

        if (!post.isEmpty()) {
            IOUtils.write(post, c.getOutputStream());
        }

        String content;

        if (c.getResponseCode() == 200) {
            content = IOUtils.toString(c.getInputStream(), c.getContentEncoding());
        } else {
            content = IOUtils.toString(c.getErrorStream(), c.getContentEncoding());
        }

        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
    }

    return j;
}

From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java

public String convertStream(HttpsURLConnection connection) throws IOException {
    InputStream input = connection.getInputStream();
    if (input == null) {
        return "";
    }/*from w  w w .j av  a2s .  co m*/

    InputStream readerStream;
    if (StringUtils.equalsIgnoreCase(connection.getContentEncoding(), "gzip")) {
        readerStream = new GZIPInputStream(connection.getInputStream());
    } else {
        readerStream = input;
    }
    String contentType = connection.getContentType();
    String charSet = null;
    if (contentType != null) {
        Matcher m = charsetPattern.matcher(contentType);
        if (m.find()) {
            charSet = m.group(1).trim().toUpperCase();
        }
    }

    Scanner inputScanner = StringUtils.isEmpty(charSet)
            ? new Scanner(readerStream, StandardCharsets.UTF_8.name())
            : new Scanner(readerStream, charSet);
    Scanner scannerWithoutDelimiter = inputScanner.useDelimiter("\\A");
    String result = scannerWithoutDelimiter.hasNext() ? scannerWithoutDelimiter.next() : null;
    inputScanner.close();
    scannerWithoutDelimiter.close();
    input.close();
    if (result == null) {
        result = "";
    }
    return result;
}

From source file:com.gmt2001.TwitchAPIv3.java

@SuppressWarnings("UseSpecificCatch")
private JSONObject GetData(request_type type, String url, String post, String oauth, boolean isJson) {
    JSONObject j = new JSONObject("{}");
    InputStream i = null;/* w w  w .  j ava  2  s . co  m*/
    String rawcontent = "";

    try {
        if (url.contains("?")) {
            url += "&utcnow=" + System.currentTimeMillis();
        } else {
            url += "?utcnow=" + System.currentTimeMillis();
        }

        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.addRequestProperty("Accept", header_accept);

        if (isJson) {
            c.addRequestProperty("Content-Type", "application/json");
        } else {
            c.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        }

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        }

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(timeout);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        c.connect();

        if (!post.isEmpty()) {
            try (OutputStream o = c.getOutputStream()) {
                IOUtils.write(post, o);
            }
        }

        String content;

        if (c.getResponseCode() == 200) {
            i = c.getInputStream();
        } else {
            i = c.getErrorStream();
        }

        if (c.getResponseCode() == 204 || i == null) {
            content = "{}";
        } else {
            content = IOUtils.toString(i, c.getContentEncoding());
        }

        rawcontent = content;

        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
        j.put("_content", content);
    } catch (JSONException ex) {
        if (ex.getMessage().contains("A JSONObject text must begin with")) {
            j = new JSONObject("{}");
            j.put("_success", true);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_exception", "");
            j.put("_exceptionMessage", "");
            j.put("_content", rawcontent);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (NullPointerException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    }

    if (i != null) {
        try {
            i.close();
        } catch (IOException ex) {
            j.put("_success", false);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_exception", "IOException");
            j.put("_exceptionMessage", ex.getMessage());
            j.put("_content", "");
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    }

    return j;
}

From source file:com.gloriouseggroll.LastFMAPI.java

@SuppressWarnings({ "null", "SleepWhileInLoop", "UseSpecificCatch" })
private JSONObject GetData(request_type type, String url, String post) {
    Date start = new Date();
    Date preconnect = start;// www  .j a  v  a2  s  .co m
    Date postconnect = start;
    Date prejson = start;
    Date postjson = start;
    JSONObject j = new JSONObject("{}");
    BufferedInputStream i = null;
    String rawcontent = "";
    int available = 0;
    int responsecode = 0;
    long cl = 0;

    try {

        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(5000);
        c.setReadTimeout(5000);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 QuorraBot/2015");
        c.setRequestProperty("Content-Type", "application/json-rpc");
        c.setRequestProperty("Content-length", "0");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        preconnect = new Date();
        c.connect();
        postconnect = new Date();

        if (!post.isEmpty()) {
            try (BufferedOutputStream o = new BufferedOutputStream(c.getOutputStream())) {
                IOUtils.write(post, o);
            }
        }

        String content;
        cl = c.getContentLengthLong();
        responsecode = c.getResponseCode();

        if (c.getResponseCode() == 200) {
            i = new BufferedInputStream(c.getInputStream());
        } else {
            i = new BufferedInputStream(c.getErrorStream());
        }

        /*
         * if (i != null) { available = i.available();
         *
         * while (available == 0 && (new Date().getTime() -
         * postconnect.getTime()) < 450) { Thread.sleep(500); available =
         * i.available(); }
         *
         * if (available == 0) { i = new
         * BufferedInputStream(c.getErrorStream());
         *
         * if (i != null) { available = i.available(); } } }
         *
         * if (available == 0) { content = "{}"; } else { content =
         * IOUtils.toString(i, c.getContentEncoding()); }
         */
        content = IOUtils.toString(i, c.getContentEncoding());
        rawcontent = content;
        prejson = new Date();
        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_available", available);
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
        j.put("_content", content);
        postjson = new Date();
    } catch (JSONException ex) {
        if (ex.getMessage().contains("A JSONObject text must begin with")) {
            j = new JSONObject("{}");
            j.put("_success", true);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "MalformedJSONData (HTTP " + responsecode + ")");
            j.put("_exceptionMessage", "");
            j.put("_content", rawcontent);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (NullPointerException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    }

    if (i != null) {
        try {
            i.close();
        } catch (IOException ex) {
            j.put("_success", false);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "IOException");
            j.put("_exceptionMessage", ex.getMessage());
            j.put("_content", "");

            if (Quorrabot.enableDebugging) {
                com.gmt2001.Console.err.printStackTrace(ex);
            } else {
                com.gmt2001.Console.err.logStackTrace(ex);
            }
        }
    }

    if (Quorrabot.enableDebugging) {
        com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData Timers "
                + (preconnect.getTime() - start.getTime()) + " " + (postconnect.getTime() - start.getTime())
                + " " + (prejson.getTime() - start.getTime()) + " " + (postjson.getTime() - start.getTime())
                + " " + start.toString() + " " + postjson.toString());
        com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData Exception " + j.getString("_exception")
                + " " + j.getString("_exceptionMessage"));
        com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData HTTP/Available " + j.getInt("_http") + "("
                + responsecode + ")/" + j.getInt("_available") + "(" + cl + ")");
        com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData RawContent[0,100] "
                + j.getString("_content").substring(0, Math.min(100, j.getString("_content").length())));
    }

    return j;
}

From source file:com.gloriouseggroll.DonationHandlerAPI.java

@SuppressWarnings({ "null", "SleepWhileInLoop", "UseSpecificCatch" })
private JSONObject GetData(request_type type, String url, String post) {
    Date start = new Date();
    Date preconnect = start;/*w  w  w . j  a va 2s  .  c o  m*/
    Date postconnect = start;
    Date prejson = start;
    Date postjson = start;
    JSONObject j = new JSONObject("{}");
    BufferedInputStream i = null;
    String rawcontent = "";
    int available = 0;
    int responsecode = 0;
    long cl = 0;

    try {

        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(5000);
        c.setReadTimeout(5000);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 QuorraBot/2015");
        c.setRequestProperty("Content-Type", "application/json-rpc");
        c.setRequestProperty("Content-length", "0");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        preconnect = new Date();
        c.connect();
        postconnect = new Date();

        if (!post.isEmpty()) {
            try (BufferedOutputStream o = new BufferedOutputStream(c.getOutputStream())) {
                IOUtils.write(post, o);
            }
        }

        String content;
        cl = c.getContentLengthLong();
        responsecode = c.getResponseCode();

        if (c.getResponseCode() == 200) {
            i = new BufferedInputStream(c.getInputStream());
        } else {
            i = new BufferedInputStream(c.getErrorStream());
        }

        /*
         * if (i != null) { available = i.available();
         *
         * while (available == 0 && (new Date().getTime() -
         * postconnect.getTime()) < 450) { Thread.sleep(500); available =
         * i.available(); }
         *
         * if (available == 0) { i = new
         * BufferedInputStream(c.getErrorStream());
         *
         * if (i != null) { available = i.available(); } } }
         *
         * if (available == 0) { content = "{}"; } else { content =
         * IOUtils.toString(i, c.getContentEncoding()); }
         */
        content = IOUtils.toString(i, c.getContentEncoding());
        rawcontent = content;
        prejson = new Date();
        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_available", available);
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
        j.put("_content", content);
        postjson = new Date();
    } catch (JSONException ex) {
        if (ex.getMessage().contains("A JSONObject text must begin with")) {
            j = new JSONObject("{}");
            j.put("_success", true);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "MalformedJSONData (HTTP " + responsecode + ")");
            j.put("_exceptionMessage", "");
            j.put("_content", rawcontent);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (NullPointerException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    }

    if (i != null) {
        try {
            i.close();
        } catch (IOException ex) {
            j.put("_success", false);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "IOException");
            j.put("_exceptionMessage", ex.getMessage());
            j.put("_content", "");

            if (Quorrabot.enableDebugging) {
                com.gmt2001.Console.err.printStackTrace(ex);
            } else {
                com.gmt2001.Console.err.logStackTrace(ex);
            }
        }
    }

    if (Quorrabot.enableDebugging) {
        com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData Timers "
                + (preconnect.getTime() - start.getTime()) + " " + (postconnect.getTime() - start.getTime())
                + " " + (prejson.getTime() - start.getTime()) + " " + (postjson.getTime() - start.getTime())
                + " " + start.toString() + " " + postjson.toString());
        com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData Exception "
                + j.getString("_exception") + " " + j.getString("_exceptionMessage"));
        com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData HTTP/Available "
                + j.getInt("_http") + "(" + responsecode + ")/" + j.getInt("_available") + "(" + cl + ")");
        com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData RawContent[0,100] "
                + j.getString("_content").substring(0, Math.min(100, j.getString("_content").length())));
    }

    return j;
}

From source file:com.gmt2001.YouTubeAPIv3.java

@SuppressWarnings({ "null", "SleepWhileInLoop", "UseSpecificCatch" })
private JSONObject GetData(request_type type, String url, String post) {
    Date start = new Date();
    Date preconnect = start;//from  w  ww .j  a  v  a  2s .c  om
    Date postconnect = start;
    Date prejson = start;
    Date postjson = start;
    JSONObject j = new JSONObject("{}");
    BufferedInputStream i = null;
    String rawcontent = "";
    int available = 0;
    int responsecode = 0;
    long cl = 0;

    try {
        if (url.contains("?") && !url.contains("oembed?")) {
            url += "&utcnow=" + System.currentTimeMillis();
        } else {
            if (!url.contains("oembed?")) {
                url += "?utcnow=" + System.currentTimeMillis();
            }
        }

        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(5000);
        c.setReadTimeout(5000);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");
        c.setRequestProperty("Content-Type", "application/json-rpc");
        c.setRequestProperty("Content-length", "0");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        preconnect = new Date();
        c.connect();
        postconnect = new Date();

        if (!post.isEmpty()) {
            try (BufferedOutputStream o = new BufferedOutputStream(c.getOutputStream())) {
                IOUtils.write(post, o);
            }
        }

        String content;
        cl = c.getContentLengthLong();
        responsecode = c.getResponseCode();

        if (c.getResponseCode() == 200) {
            i = new BufferedInputStream(c.getInputStream());
        } else {
            i = new BufferedInputStream(c.getErrorStream());
        }

        /*
         * if (i != null) { available = i.available();
         *
         * while (available == 0 && (new Date().getTime() -
         * postconnect.getTime()) < 450) { Thread.sleep(500); available =
         * i.available(); }
         *
         * if (available == 0) { i = new
         * BufferedInputStream(c.getErrorStream());
         *
         * if (i != null) { available = i.available(); } } }
         *
         * if (available == 0) { content = "{}"; } else { content =
         * IOUtils.toString(i, c.getContentEncoding()); }
         */
        content = IOUtils.toString(i, c.getContentEncoding());
        rawcontent = content;
        prejson = new Date();
        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_available", available);
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
        j.put("_content", content);
        postjson = new Date();
    } catch (JSONException ex) {
        if (ex.getMessage().contains("A JSONObject text must begin with")) {
            j = new JSONObject("{}");
            j.put("_success", true);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "MalformedJSONData (HTTP " + responsecode + ")");
            j.put("_exceptionMessage", "");
            j.put("_content", rawcontent);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (NullPointerException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (PhantomBot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (PhantomBot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (PhantomBot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (PhantomBot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    }

    if (i != null) {
        try {
            i.close();
        } catch (IOException ex) {
            j.put("_success", false);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "IOException");
            j.put("_exceptionMessage", ex.getMessage());
            j.put("_content", "");

            if (PhantomBot.enableDebugging) {
                com.gmt2001.Console.err.printStackTrace(ex);
            } else {
                com.gmt2001.Console.err.logStackTrace(ex);
            }
        }
    }

    if (PhantomBot.enableDebugging) {
        com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetData Timers "
                + (preconnect.getTime() - start.getTime()) + " " + (postconnect.getTime() - start.getTime())
                + " " + (prejson.getTime() - start.getTime()) + " " + (postjson.getTime() - start.getTime())
                + " " + start.toString() + " " + postjson.toString());
        com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetData Exception " + j.getString("_exception")
                + " " + j.getString("_exceptionMessage"));
        com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetData HTTP/Available " + j.getInt("_http")
                + "(" + responsecode + ")/" + j.getInt("_available") + "(" + cl + ")");
        com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetData RawContent[0,100] "
                + j.getString("_content").substring(0, Math.min(100, j.getString("_content").length())));
    }

    return j;
}

From source file:com.gmt2001.TwitchAPIv5.java

@SuppressWarnings("UseSpecificCatch")
private JSONObject GetData(request_type type, String url, String post, String oauth, boolean isJson) {
    JSONObject j = new JSONObject("{}");
    InputStream i = null;//from ww w . ja v  a 2 s . c  o m
    String content = "";

    try {
        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();
        c.addRequestProperty("Accept", header_accept);
        c.addRequestProperty("Content-Type", isJson ? "application/json" : "application/x-www-form-urlencoded");

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        } else {
            if (!this.oauth.isEmpty()) {
                c.addRequestProperty("Authorization", "OAuth " + oauth);
            }
        }

        c.setRequestMethod(type.name());
        c.setConnectTimeout(timeout);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        c.connect();

        if (!post.isEmpty()) {
            try (OutputStream o = c.getOutputStream()) {
                IOUtils.write(post, o);
            }
        }

        if (c.getResponseCode() == 200) {
            i = c.getInputStream();
        } else {
            i = c.getErrorStream();
        }

        if (c.getResponseCode() == 204 || i == null) {
            content = "{}";
        } else {
            // default to UTF-8, it'll probably be the best bet if there's
            // no charset specified.
            String charset = "utf-8";
            String ct = c.getContentType();
            if (ct != null) {
                String[] cts = ct.split(" *; *");
                for (int idx = 1; idx < cts.length; ++idx) {
                    String[] val = cts[idx].split("=", 2);
                    if (val[0] == "charset" && val.length > 1) {
                        charset = val[1];
                    }
                }
            }

            if ("gzip".equals(c.getContentEncoding())) {
                i = new GZIPInputStream(i);
            }

            content = IOUtils.toString(i, charset);
        }

        j = new JSONObject(content);
        fillJSONObject(j, true, type.name(), post, url, c.getResponseCode(), "", "", content);
    } catch (Exception ex) {
        Throwable rootCause = ex;
        while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
            rootCause = rootCause.getCause();
        }

        fillJSONObject(j, false, type.name(), post, url, 0, ex.getClass().getSimpleName(), ex.getMessage(),
                content);
        com.gmt2001.Console.debug
                .println("Failed to get data [" + ex.getClass().getSimpleName() + "]: " + ex.getMessage());
    } finally {
        if (i != null) {
            try {
                i.close();
            } catch (IOException ex) {
                fillJSONObject(j, false, type.name(), post, url, 0, "IOException", ex.getMessage(), content);
                com.gmt2001.Console.err.println("IOException: " + ex.getMessage());
            }
        }
    }

    return j;
}