๋ด๊ฐ ํ๊ณ ์ถ์๋ ๊ฒ์
http:~ ๋ก ๋ ์ฃผ์์ ๋ด๊ธด API data ๋ฅผ
๋ด๊ฐ ๊ตฌํํ ์๋ฒ์์ ์ ๊ณตํ๋ ๊ฑฐ ์์.
๊ณ ๋ก ๋ด๊ฐ ๊ตฌํํ ์๋ฒ์์ ํ๋ก์ ์๋ฒ์ ์ญํ ์ ํด์ฃผ์ด์ผ ํ๋ ๊ฒ.
์ด๋ ๋ญ RestTemplete ์ด๋ WebClient ๋ ์ค์นํ๊ณ ์ ํ ํ๊ณ ... ๋๋ฌด ๊ท์ฐฎ์์.
๊ทธ๋์ ๊ฐ๋จ ver ๋ก requestUtil ์ ๋ง๋ค์ด๋ณด์๋ค.
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
public class RequestUtil {
public static String restRequest(String requestUrl){
String result="";
//๋ณด๋ผ ํ๋ผ๋ฉํฐ ์
ํ
// MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
// params.add("id", id);
//ํค๋์
ํ
HttpHeaders headers = new HttpHeaders();
headers.add("ํค๋์ด๋ฆ", "application/json; charset=utf-8");
//Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36
//ํ๋ผ๋ฉํฐ์ ํค์ด ํฉ์น๊ธฐ
// HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(headers);
//RestTemplate ์ด๊ธฐํ
RestTemplate rt = new RestTemplate();
//์ ์ก ๋ฐ ๊ฒฐ๊ณผ ์ฒ๋ฆฌ
ResponseEntity<String> response = rt.exchange(
requestUrl,
HttpMethod.GET,
entity,
String.class
);
result = response.getBody();//๋ฆฌํด๋๋ ๊ฒฐ๊ณผ์ body๋ฅผ ์ ์ฅ.
return result;
}
}
๊ทธ๋ฆฌ๊ณ ์ฌ์ฉํ๊ธฐ๋ฅผ ์ํ๋ ์์ ์์ ๋ค๋ฅธ Util๋ค ๊บผ๋ด์ฐ๋ฏ์ด ๊บผ๋ด์ด์ ๋ฃ์ด์ฃผ๋ฉด ๋จ.
RequestUtil.restRequest("HTTP://~");
์ด๋ ๊ฒ ํด์ dsResult ์ ๋ฃ์ด์ ํ๋ก ํธ์์ ๋ฐ์์ฃผ๋ฉด
์์ ๊ฐ์ ํํ๋ก return ๋จ.
๋ณธ์ธ์ ๊ฒฝ์ฐ ๊ธฐ์กด http://~ ์ฃผ์์ ์ด๋ฏธ์ง๊ฐ ๋ด๊ฒจ ์์ด์ ์์ ๊ฐ์ ํํ๋ก ๋จ๊ณ ..
์๋ง json ํํ๋ก ์ด๋ค ๊ฐ์ด ๋ค์ด์์๋ค๋ฉด, ๊ทธ๋๋ก ๋ด๊ณ ์๋ ํํ์ผ ๊ฒ ์ด๋ค.
์ ๋ถํ ๋ฃ์ด์ ์ฝ๊ฒ ์ฌ์ฉํด๋ณด์๊ธธ...