티스토리 뷰

반응형


.API Connection


API Connection을 위한 예제를 살펴보려고 한다.

예제에서는 request 후 response로 JSON Object를 받는 형태이다.


JSON Object 사용을 위해 JSON.simple import 가 필요하다.

plugin으로 사용 시 "여기"를,

jar 파일을 사용할 경우 "여기"를 참고해보면 좋을 것 같다.


JSON Parser 관련 정보는 아래 글을 참고해보자!

[API] Java JSONParser


.example01 (GET)


API 정보

curl -X GET {BASE_URL}/example01 

-H 'Authorization: {AUTH_KEY}' 

-H 'Content-Type: application/json'


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 
public JSONObject getExample() {
    HttpURLConnection conn = null;
    JSONObject responseJson = null;
 
    try {
        URL url = new URL(GlobalData.HOST_URL + "/example01");
        conn = (HttpURLConnection) url.openConnection();
        // Authorization 정보를 head에 넣어주자.
        conn.setRequestProperty("Authorization", KeyManger.getInstance().getKey());
        // Content-Type 도 마찬가지로 !
        conn.setRequestProperty("Content-Type""application/json");
 
        int responseCode = conn.getResponseCode();
        if (responseCode == 401) {
            System.out.println("401:: Header를 확인해주세요.");
        } else if (responseCode == 500) {
            System.out.println("500:: 서버 에러");
        } else { // response
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
 
            responseJson = new JSONObject(sb.toString());
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        System.out.println("not JSON Format response");
        e.printStackTrace();
    }
    return responseJson;
}
cs



.example02 (POST)


API 정보

curl -X POST {BASE_URL}/start

-H 'X-Auth-Token: {X_AUTH_TOKEN}'

-H 'Content-Type: application/json'

-d '{ "problem": 1 }'


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
 
public String getAutoKey(String userKey, int id) {
 
    HttpURLConnection conn = null;
    JSONObject responseJson = null;
    String response = null;
    String startParams = "/" + userKey + "/" + Integer.toString(id);
 
    try {
        URL url = new URL(GlobalData.HOST_URL + "/start");
        conn = (HttpURLConnection) url.openConnection();
        // Set request mothod
        conn.setRequestMethod("POST");
        // Set Header
        conn.setRequestProperty("X-Auth-Token", userKey);
        conn.setRequestProperty("Content-Type""application/json");
        // Set Data
        conn.setDoOutput(true);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
        JSONObject commands = new JSONObject();
        commands.put("problem"1);
        bw.write(commands.toString());
        bw.flush();
        bw.close();
 
        int responseCode = conn.getResponseCode();
        if (responseCode == 200) { // 성공
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
 
            responseJson = new JSONObject(sb.toString());
            response = responseJson.getString("auth_key");
        } else {
            response = String.valueOf(responseCode);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        System.out.println("not JSON Format response");
        e.printStackTrace();
    }
 
    return response;
}
cs


.example03 (PUT)


API 정보

curl -X PUT {BASE_URL}/simulate

-H 'Authorization: {AUTH_KEY}'

-H 'Content-Type: application/json'

-d '{ "commands": [ { "something_id": 0,

"command": [2, 5, 4, 1, 6] } ... ] }'


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
 
public JSONObject setSimulate(JSONArray commandArrays) {
    HttpURLConnection conn = null;
    JSONObject responseJson = null;
 
    try {
 
        URL url = new URL(GlobalData.HOST_URL + "/simulate");
        conn = (HttpURLConnection) url.openConnection();
        // set request method
        conn.setRequestMethod("PUT");
        // set Header
        conn.setRequestProperty("Authorization", KeyManger.getInstance().getKey());
        conn.setRequestProperty("Content-Type""application/json");
        // set Data
        conn.setDoOutput(true);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
        JSONObject commands = new JSONObject();
        commands.put("commands", commandArrays);
        bw.write(commands.toString());
        bw.flush();
        bw.close();
 
        int responseCode = conn.getResponseCode();
        if (responseCode == 400) {
            System.out.println"400:: 해당 명령 실행 불가");
        } else if (responseCode == 401) {
            System.out.println("401:: Header 오류");
        } else if (responseCode == 500) {
            System.out.println("500:: 서버 에러");
        } else { // success
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
 
            responseJson = new JSONObject(sb.toString());
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        System.out.println("not JSON Format response");
        e.printStackTrace();
    }
    return responseJson;
}
cs



반응형
댓글
최근에 올라온 글
최근에 달린 댓글
링크
Total
Today
Yesterday