๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ปTech/โ˜•Java

[Java] REST API ํ˜ธ์ถœ ์ฝ”๋“œ

by _viper_ 2019. 11. 19.
๋ฐ˜์‘ํ˜•

JsonObject๋ฅผ ๋„˜๊ฒจ ๊ฒฐ๊ณผ๊ฐ’์„ ์‘๋‹ต๋ฐ›๋Š” REST API ํ˜ธ์ถœ ์ž๋ฐ” ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค.

์•„๋ž˜์™€ ๊ฐ™์ด ๋ฉ”์†Œ๋“œ๋กœ ํ•˜๋‚˜ ์ •๋ฆฌํ•ด ๋‘๋ฉด ์‚ฌ์šฉ์— ์šฉ์ดํ•ฉ๋‹ˆ๋‹ค.

    /**
     * REST API ํ˜ธ์ถœ
     *  
     * @param paramUrl
     * @param jsonObject void
     */
    private void RestCall(String paramUrl,JSONObject jsonObject){
    	try {
            URL url = new URL(paramUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("X-Auth-Token", API_KEY);            
            conn.setRequestProperty("X-Data-Type", "application/json");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);

            OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
            osw.write(jsonObject.toString());
            osw.flush();
            osw.close();
            
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            if (conn.getResponseCode() != 200) {
                System.out.println("Failed: HTTP error code : " + conn.getResponseCode());
            	throw new RuntimeException("Failed: HTTP error code : " + conn.getResponseCode());
            } else {
                System.out.println("๋ฐœ์†ก ์„ฑ๊ณต");
            }
            
            String line = null;
            while((line = br.readLine()) != null){
                System.out.println(line);
            }
            br.close();           
            conn.disconnect();
        } catch (IOException e) {
            System.out.println("RestCall Fail : " + e.getMessage());
        }
    }