카테고리 없음

java API 환경설정 세팅~! http (get,post,put) ApiConnect 만들기

르무엘 2022. 5. 24. 09:21

https://velog.io/@blackb0x/%EC%84%9C%EB%B2%84-API-%ED%86%B5%EC%8B%A0%EA%B3%BC-REST-API

 

 

서버 API 통신과 REST API

Application Programming Interface의 약자API는 한 프로그램이 다른 프로그램을 이용할 때 쓰는 인터페이스로 입출력이 데이터로 된다.어떤 특정 사이트에서 특정 데이터를 공유할 경우 어떤 방식으로 요

velog.io

기본 API 와 통신에 대해서는 위참조

[간단 요약]

서버 API(Application Programming Interface)

 REST(Representational State Transfer) API - HTTP 통신에서 어떤 자원에 대한 CRUD(Create, Read, Update, Delete) 요청을 Resource와 Method(GET, POS, DELETE등)로 표현하여 특정한 형태로 전달하는 방식

 

만들어 보기전에 기본 API 통신 이해

https://korshika.tistory.com/49

 

HTTP 통신 기본 & Rest API

■ 웹 & 통신 protocol 1) 정의 : 인터넷 상에서 통신 규약, protocol 이라고 지칭 > 웹서버와 웹 사용자의 브라우저 사이에 Hyper Text문서를 전송하기 위한 규약 (문자 그대로 text 전송) + encrypted(암호화)..

korshika.tistory.com

 

 

[HttpURLConnection  참고 아래]

https://ggoreb.tistory.com/114

 

[Java] URLConnection, URLEncoder, URLDecoder

java.net.URLConnection - URL 내용을 읽어오거나, URL 주소에 GET / POST로 데이터를 전달 할 때 사용함 - 웹 페이지나 서블릿에 데이터를 전달 수 있음 - URL --> openConnection() --> URLConnection --> getIn..

ggoreb.tistory.com

 

본격적으로 만들어 봅니다.

 

// API 설계도

public class ApiConnect {
// HTTP URL 연결
private HttpURLConnection http;

public ApiConnect(HttpURLConnection http) {
super();
this.http = http;
}

// api 요청할 메소드( get,post,put 등과 json 인자)
public void request(String method, JsonObject jsonData) throws IOException{

// 스트림 출력설정
http.setDoOutput(true);

// 메소드 설정
http.setRequestMethod(method);

//
http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
http.setRequestProperty("Transfer-Encoding", "chunked");

// 연결지속
http.setRequestProperty("Connection", "keep-alive");

// 케넥션 타임아웃 10초
http.setConnectTimeout(10000);

// 컨텐츠 조회 타임아웃 10초
http.setReadTimeout(10000);

// json 싫어서 보냄
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(http.getOutputStream()));
printWriter.write(jsonData.toString());
printWriter.flush();

}

// api 응답 response 메소드
public String response() throws IOException{

// BufferedReader 클래스 사용
BufferedReader bufferedReader = null;

// http 응답코드 받음
int status = http.getResponseCode();

// 200 으로 정상이면
if(status == HttpURLConnection.HTTP_OK) {

//  InputStreamReader 클래스안에 http 통신 값의 getInputStream 을 담음
bufferedReader = new BufferedReader(new InputStreamReader(http.getInputStream()));
}else {
bufferedReader = new BufferedReader(new InputStreamReader(http.getErrorStream()));
}
String line;
StringBuffer response = new StringBuffer();

// StringBuffer 클래스에 bufferedReader 클래스 내용 담음
while((line = bufferedReader.readLine()) != null ) {
response.append(line);
}
bufferedReader.close();

// 스트링 반환
return response.toString();

}


}

LIST