Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Main {
    private final static int TIMEOUT_CONNECTION = 5000;
    private final static int TIMEOUT_READ = 10000;

    public static String callJsonAPI(String urlString) {
        // Use HttpURLConnection as per Android 6.0 spec, instead of less efficient HttpClient
        HttpURLConnection urlConnection = null;
        StringBuilder jsonResult = new StringBuilder();

        try {
            URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setUseCaches(false);
            urlConnection.setConnectTimeout(TIMEOUT_CONNECTION);
            urlConnection.setReadTimeout(TIMEOUT_READ);
            urlConnection.connect();

            int status = urlConnection.getResponseCode();

            switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

                String line;
                while ((line = br.readLine()) != null) {
                    jsonResult.append(line).append("\n");
                }
                br.close();
            }
        } catch (MalformedURLException e) {
            System.err.print(e.getMessage());
            return e.getMessage();
        } catch (IOException e) {
            System.err.print(e.getMessage());
            return e.getMessage();
        } finally {
            if (urlConnection != null) {
                try {
                    urlConnection.disconnect();
                } catch (Exception e) {
                    System.err.print(e.getMessage());
                }
            }
        }
        return jsonResult.toString();
    }
}