Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;

import java.net.URL;
import java.util.ArrayList;
import javax.net.ssl.HttpsURLConnection;

public class Main {
    /**
     *
     * @param url - String
     * @param reqParam refer POST method
     * @param accessToken - String
     * @return ArrayList<String> 0: responseBody
     *                          1: responseCode
     */
    public static ArrayList<String> getResponse(String url, String reqParam, String accessToken) {
        StringBuilder response = null;
        StringBuilder urlBuilder = null;
        BufferedReader in = null;
        HttpsURLConnection con = null;
        ArrayList<String> responseList = new ArrayList<String>();
        int responseCode = -1;
        try {
            response = new StringBuilder();

            urlBuilder = new StringBuilder();
            urlBuilder.append(url);
            urlBuilder.append("?").append(reqParam);
            urlBuilder.append("&access_token=").append(accessToken);

            URL urlObj = new URL(urlBuilder.toString());

            con = (HttpsURLConnection) urlObj.openConnection();
            con.setRequestMethod("GET");
            con.setDoInput(true);
            con.setDoOutput(false);

            con.setRequestProperty("Authorization: Bearer", accessToken);
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            responseCode = con.getResponseCode();
            String inputLine = "";
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }

        } catch (Exception e) {
            in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            String inputLine = "";

            try {
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            if (responseCode == -1) {

            } else {

                System.out.println(response.toString());
            }
        }

        finally {
            try {
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        responseList.add(response.toString());
        responseList.add(String.valueOf(responseCode));
        return responseList;

    }
}