Jar 등록
[ 1. json.jar 다운로드 ]
[ 2. 프로젝트 내부에 lib 폴더 생성 및 jar파일 옮기기 ]
[ 3. 프로젝트 우 클릭 → Build Path → Configure Build Path... ]
[ 4. Add Jars... → jar파일 선택 → OK ]
Get
rest api에서 사용하는 http 메서드는 총 4가지로 get, post, put, delete가 있습니다.
그 중 get은 데이터를 조회해오는 목적으로 주로 사용됩니다.
get으로 테스트를 해볼 것은 서버로 데이터는 전달하지 않고 서버에서 객체 값과 배열 값을 각각 받아오는 코드를 작성해보겠습니다.
먼저 객체값을 받아오는 코드를 작성해보겠습니다.
rest api를 호출해볼 수 있는 포스트맨에서 다음과 같이 호출되는 것을 자바로 작성해보겠습니다
package httpconnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class HttpConnection {
public static void main(String[] args) {
getJson();
}
public static void getJson() {
try {
URL url = new URL("http://localhost:8080/rest/getJson");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET"); // http 메서드
conn.setRequestProperty("Content-Type", "application/json"); // header Content-Type 정보
conn.setRequestProperty("auth", "myAuth"); // header의 auth 정보
conn.setDoOutput(true); // 서버로부터 받는 값이 있다면 true
// 서버로부터 데이터 읽어오기
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = br.readLine()) != null) { // 읽을 수 있을 때 까지 반복
sb.append(line);
}
JSONObject obj = new JSONObject(sb.toString()); // json으로 변경 (역직렬화)
System.out.println("code= " + obj.getInt("code") + " / message= " + obj.getString("message"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
위와 같이 작성된 코드를 실행해보면 다음과 같이 콘솔 창에 출력됩니다.
code= 0 / message= Success
이번엔 배열을 받아와 보겠습니다.
포스트맨에서 다음과 같이 호출되는 것을 자바로 작성해보겠습니다.
package httpconnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;
public class HttpConnection {
public static void main(String[] args) {
getJsonArray();
}
public static void getJsonArray() {
try {
URL url = new URL("http://localhost:8080/rest/getJsonArray");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET"); // http 메서드
conn.setRequestProperty("Content-Type", "application/json"); // header Content-Type 정보
conn.setRequestProperty("auth", "myAuth"); // header의 auth 정보
conn.setDoOutput(true); // 서버로부터 받는 값이 있다면 true
// 서버로부터 데이터 읽어오기
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = br.readLine()) != null) { // 읽을 수 있을 때 까지 반복
sb.append(line);
}
JSONArray array = new JSONArray(sb.toString()); // json으로 변경 (역직렬화)
for(int i=0; i<array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
System.out.println("index= " + i + " / code= " + obj.getInt("code") + " / message= " + obj.getString("message"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
위와 같이 작성된 코드를 실행해보면 다음과 같이 출력됩니다.
index= 0 / code= 0 / message= Success
index= 1 / code= -1 / message= Fail
Post
post는 일반적으로 데이터를 삽입할 때 사용되는 http 메서드입니다.
이번엔 post를 이용하여 json데이터를 서버쪽에 전달해보는 코드를 작성해보겠습니다.
포스트맨에서는 다음과 같이 실행이 되는 것을 자바로 작성해보겠습니다.
package httpconnection;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class HttpConnection {
public static void main(String[] args) {
post();
}
public static void post() {
try {
URL url = new URL("http://localhost:8080/rest/post");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST"); // http 메서드
conn.setRequestProperty("Content-Type", "application/json"); // header Content-Type 정보
conn.setDoInput(true); // 서버에 전달할 값이 있다면 true
conn.setDoOutput(true); // 서버로부터 받는 값이 있다면 true
// 서버에 데이터 전달
JSONObject obj = new JSONObject();
obj.put("name", "J4J");
obj.put("age", 123);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
bw.write(obj.toString()); // 버퍼에 담기
bw.flush(); // 버퍼에 담긴 데이터 전달
bw.close();
// 서버로부터 데이터 읽어오기
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = br.readLine()) != null) { // 읽을 수 있을 때 까지 반복
sb.append(line);
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
출력 값은 나오지 않기에 당연히 콘솔 창에는 아무것도 찍히지 않습니다.
Put
put은 보통 데이터를 수정할 때 사용되는 http메서드입니다.
put을 이용해서는 서버에 배열로 된 데이터를 넘겨주고 서버로부터 객체를 리턴 받아 보겠습니다.
포스트맨에서 다음과 같이 실행되는 것을 자바로 구현해보겠습니다.
package httpconnection;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;
public class HttpConnection {
public static void main(String[] args) {
put();
}
public static void put() {
try {
URL url = new URL("http://localhost:8080/rest/put");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("PUT"); // http 메서드
conn.setRequestProperty("Content-Type", "application/json"); // header Content-Type 정보
conn.setDoInput(true); // 서버에 전달할 값이 있다면 true
conn.setDoOutput(true); // 서버로부터 받는 값이 있다면 true
// 서버에 데이터 전달
JSONArray array = new JSONArray();
JSONObject obj1 = new JSONObject();
obj1.put("name", "J4J");
obj1.put("age", 123);
JSONObject obj2 = new JSONObject();
obj2.put("name", "ABC");
obj2.put("age", 456);
array.put(obj1);
array.put(obj2);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
bw.write(array.toString()); // 버퍼에 담기
bw.flush(); // 버퍼에 담긴 데이터 전달
bw.close();
// 서버로부터 데이터 읽어오기
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = br.readLine()) != null) { // 읽을 수 있을 때 까지 반복
sb.append(line);
}
JSONObject obj = new JSONObject(sb.toString()); // json으로 변경 (역직렬화)
System.out.println("code= " + obj.getInt("code") + " / message= " + obj.getString("message"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
위와 같이 코드를 작성하고 실행하면 콘솔창에 다음과 같이 출력됩니다.
code= 0 / message= Success
Delete
delete는 데이터를 삭제할 때 주로 사용되는 http 메서드입니다.
delete를 이용해서는 post나 put처럼 request body로 데이터를 넘겨주는 것이 아니라 파라미터, 즉 쿼리 문자열의 형태로 데이터를 넘겨줘 보겠습니다.
포스트맨에서 다음과 같이 실행되는 것을 자바로 구현해보겠습니다.
package httpconnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpConnection {
public static void main(String[] args) {
delete();
}
public static void delete() {
try {
URL url = new URL("http://localhost:8080/rest/delete?name=J4J&age=123");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("DELETE"); // http 메서드
conn.setDoInput(true); // 서버에 전달할 값이 있다면 true
// 서버로부터 데이터 읽어오기
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = br.readLine()) != null) { // 읽을 수 있을 때 까지 반복
sb.append(line);
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
코드를 작성하고 실행해봐도 서버에서 넘어오는 데이터는 없기 때문에 콘솔 창에는 아무것도 출력되지 않습니다.
이상으로 url connection을 이용한 api 호출에 대해 간단하게 알아보는 시간이었습니다.
읽어주셔서 감사합니다.
'BE > JAVA' 카테고리의 다른 글
[Java] JAVA로 업다운(Up&Down) 게임 구현하기 (0) | 2023.05.17 |
---|---|
[Java] static변수와 static 메소드 (0) | 2023.05.17 |
[JAVA] 정규 표현식(Regular Expression) (0) | 2022.05.13 |
[JAVA] 자바 스트림(Stream) 예제부터 사용법까지 정리 (0) | 2022.05.12 |
[Java] String 문자열을 char 배열로 변환하기 (0) | 2022.05.10 |