OkHttp 는 REST API, HTTP 통신을 간편하게 구현할 수 있도록 다양한 기능을 제공해주는 자바 라이브러리
OkHttp 라이브러리를 사용하기 위해서 메이븐 Dependencies 설정이 필요
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.10.0</version>
</dependency>
Get 방식
URL url = new URL(requestUrl);
OkHttpClient client = new OkHttpClient();
Request request = new Requester.Builder()
.url(url)
.header("Content-type", "")
.build();
Response response = client.newCall(request).execute();
Post 방식
URL url = new URL(requestUrl);
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
Request request = new Requester.Builder()
.url(url)
.header("Content-type", "application/json")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
* URL 클래스
=> 주요 생성자
https://, www.naver.com/, index.html, :8080
(protocol, host, file, port)
비동기 요청
execute() 대신 enqueue() 사용
*Callback에는 다음 인터페이스를 구현해야함
public interface Callback{
void onFailure(Call call, IOException e);
void onResponse(Call call, Response response) throws IOException;
}
client.newCall(request).enqueue(new Callback(){
@Override
public void onFailure(Call call, IOException e){
System.err.println("error");
}
@Override
public void onResponse(Call call, Response response) thorws IOException{
ResponseBody body = response.body();
System.out.println(body.string());
body.close();
}
});
'SPRING' 카테고리의 다른 글
Tomcat 기동 시 폴더 생성 (1) | 2023.07.13 |
---|---|
Jackson과 ObjectMapper (0) | 2023.01.03 |
접근제어지시자와 정보은닉 (0) | 2022.09.27 |
Properties 란? (0) | 2022.09.19 |
댓글