Back-end/Spring

[Spring] ๊ฐ„๋‹จํ•˜๊ฒŒ HTTP POST ์š”์ฒญํ•˜๊ธฐ

๐Ÿ’ก POST ์š”์ฒญ์ด๋ž€?

  • ์„œ๋ฒ„์— ์š”์ฒญํ•˜๋Š” ๋ฐฉ์‹
  • ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์„œ๋ฒ„์— ์š”์ฒญ์„ ํ•  ๋•Œ ์ œ๊ณตํ•ด์•ผํ•˜๋Š” ์ž์›์ด ์žˆ์„ ๋•Œ 
  • Get๋ฐฉ์‹์€ ์š”์ฒญํ•˜๋Š” ์ž์›์„ URL์— ๋’ค์— ๋ณด๋‚ด๋Š” ๋ฐ˜๋ฉด
  • POST๋ฐฉ์‹์€ URL์— ๋ถ™์ด์ง€ ์•Š๊ณ  ๋”ฐ๋กœ ๋ฐ์ดํ„ฐ(Body)๋ฅผ ๋งŒ๋“ค์–ด ๋ณด๋‚ธ๋‹ค.

 

๐Ÿ” Spring Framework์—์„œ POST ์š”์ฒญ ํ•˜๊ธฐ 

1. Body ๋งŒ๋“ค๊ธฐ

 

Body๋Š” ๋ณดํ†ต key, value์˜ ์Œ์œผ๋กœ ์ด๋ฃจ์–ด์ง€๊ธฐ ๋•Œ๋ฌธ์— ์ž๋ฐ”์—์„œ ์ œ๊ณตํ•ด์ฃผ๋Š” MultiValueMap ํƒ€์ž…์„ ์‚ฌ์šฉํ•ด์•ผํ•œ๋‹ค.

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add('')

MultiValueMap ํƒ€์ž…์œผ๋กœ ๋งŒ๋“ค์–ด์ค€ ๋ณ€์ˆ˜์— add()๋ฅผ ์‚ฌ์šฉํ•ด ๋ณด๋‚ผ ๋ฐ์ดํ„ฐ๋ฅผ ์ถ”๊ฐ€ํ•ด์ค€๋‹ค.

 

2. Header ๋งŒ๋“ค๊ธฐ

HTTP POST๋ฅผ ์š”์ฒญํ• ๋•Œ ๋ณด๋‚ด๋Š” ๋ฐ์ดํ„ฐ(Body)๋ฅผ ์„ค๋ช…ํ•ด์ฃผ๋Š” ํ—ค๋”(Header)๋„ ๋งŒ๋“ค์–ด์„œ ๊ฐ™์ด ๋ณด๋‚ด์ค˜์•ผ ํ•œ๋‹ค.

HttpHeaders headers = new HttpHeaders();
headers.add("");

Spring Framework์—์„œ ์ œ๊ณตํ•ด์ฃผ๋Š” HttpHeaders ํด๋ž˜์Šค๋Š” Header๋ฅผ ๋งŒ๋“ค์–ด์ค€๋‹ค.

add()๋ฅผ ์‚ฌ์šฉํ•ด Header์— ๋“ค์–ด๊ฐˆ ๋‚ด์šฉ์„ ์ถ”๊ฐ€ํ•ด์ฃผ์ž.

 

3. ์š”์ฒญํ•˜๊ธฐ ์œ„ํ•ด ํ—ค๋”(Header)์™€ ๋ฐ์ดํ„ฐ(Body) ํ•ฉ์น˜๊ธฐ

HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);

Spring Framework์—์„œ ์ œ๊ณตํ•ด์ฃผ๋Š” HttpEntity ํด๋ž˜์Šค๋Š” Header์™€ Body๋ฅผ ํ•ฉ์ณ์ค€๋‹ค.

 

4. POST ์š”์ฒญํ•ด๋ณด๊ธฐ

RestTemplate rt = new RestTemplate();

ResponseEntity<String> response = rt.exchange(
                "https://{์š”์ฒญํ•  ์„œ๋ฒ„ ์ฃผ์†Œ}", //{์š”์ฒญํ•  ์„œ๋ฒ„ ์ฃผ์†Œ}
                HttpMethod.POST, //{์š”์ฒญํ•  ๋ฐฉ์‹}
                entity, // {์š”์ฒญํ•  ๋•Œ ๋ณด๋‚ผ ๋ฐ์ดํ„ฐ}
                String.class {์š”์ฒญ์‹œ ๋ฐ˜ํ™˜๋˜๋Š” ๋ฐ์ดํ„ฐ ํƒ€์ž…}
);

 

Spring Framework์—์„œ๋Š” ์„œ๋ฒ„์— ์š”์ฒญ์„ ํŽธํ•˜๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•œ RestTemplate ํด๋ž˜์Šค๋ฅผ ์ œ๊ณตํ•ด์ค€๋‹ค.


๐Ÿ” RestTemplate์ด๋ž€?

 

The RestTemplate offers templates for common scenarios by HTTP method, in addition to the generalized exchange and execute methods that support of less frequent cases.

 

HTTP ๋ฉ”์†Œ๋“œ์— ์˜ํ•œ ํ‰๋ฒ”ํ•œ ๊ธฐ๋Šฅ ํ…œํ”Œ๋ฆฟ์„ ์ œ๊ณตํ•ด์ฃผ๊ณ , ๋” ๋‚˜์•„๊ฐ€ ํŠน๋ณ„ํ•œ ์ผ€์ด์Šค๋ฅผ ์ง€์›ํ•˜๋Š” exchange์™€ execute ๋ฉ”์†Œ๋“œ๋ฅผ ์ œ๊ณตํ•ด์ค€๋‹ค.

 

exchage() : ๋ชจ๋“  HTTP ์š”์ฒญ ๋ฉ”์†Œ๋“œ๋ฅผ ์ง€์›ํ•˜๋ฉฐ ์›ํ•˜๋Š” ์„œ๋ฒ„์— ์š”์ฒญ์‹œ์ผœ์ฃผ๋Š” ๋ฉ”์†Œ๋“œ

 

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html

 

RestTemplate (Spring Framework 5.2.9.RELEASE API)

Synchronous client to perform HTTP requests, exposing a simple, template method API over underlying HTTP client libraries such as the JDK HttpURLConnection, Apache HttpComponents, and others. The RestTemplate offers templates for common scenarios by HTTP m

docs.spring.io

 

response์— ์„œ๋ฒ„์—์„œ ์‘๋‹ตํ•ด์ค€ ๋ฐ์ดํ„ฐ๊ฐ€ ์ €์žฅ๋  ๊ฒƒ์ด๋‹ค.

 

๋ฐ˜์‘ํ˜•