[PowerShell] Invoke-WebRequest 를 이용한 웹호출 POST,GET

728x90
반응형

 

 

프로젝트를 진행함에 있어서, 각 구성원들간에 정보를 공유해야 할 사항이 많이 발생하는 있어서, 각 구성원들간에 정보를 공유해야 할 사항이 많이 발생합니다. 이를 조금이나마 효율적으로 하기 위해서 별도의 서버를 구성해서

각 구성원들에게 메신저API를 통해서 알람이 발송되도록 진행을 했는데요.

 

이때 PowerShell 을 이용해서 웹 RESTFul API 를 호출 했습니다. 

Curl을 이용해도되지만, Jenkins 가 Windows 서버에 설치가 되어 있어서 PowerShell 을 이용했습니다. 

 


 

Invoke-WebRequest

웹 RESTFul API의 호출은 PowerShell 의 Invoke-WebRequst 명령어를 이용해서 진행했습니다.

주로 사용하는 Method Type이 GET 과 POST 방식이 있을 텐데요. 

각각 호출 하는 방식에 대해서 정리해보겠습니다.

 

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-7.1 

 

Invoke-WebRequest (Microsoft.PowerShell.Utility) - PowerShell

The Invoke-WebRequest cmdlet sends HTTP and HTTPS requests to a web page or web service. It parses the response and returns collections of links, images, and other significant HTML elements. This cmdlet was introduced in PowerShell 3.0. Beginning in PowerS

docs.microsoft.com


 

GET 방식

GET 방식은 모든 Param 의 정보가 URL에 포함되어 있는 구조이다 보니, 

호출하는 방식이 간편합니다.

Invoke-WebRequest "http://localhost:8888/api/Send?param1=PARAM1&param2=PARAM2"

Invoke-WebRequest -Method GET -Uri http://localhost:8888/api/Send?param1=PARAM1&param2=PARAM2

 


 

POST 방식

사실 포스팅의 목적은 POST 방식을 정리하기 위함이였습니다. 

POST 방식은 Body 부분에 데이터를 포함해서 전달하는 방식이기 때문에 ContentType 에 대해서 추가적인 설정이 필요한데요.

또한 PowerShell 을 이용하다 보면, 한글이 깨지는 현상도 같이 발생해서, 

이를 포함해서 정리했습니다. 

$text="param1=PARAM1&param2=PARAM2"
$postParam=[System.Text.Encoding]::UTF8.GetBytes($text)

Invoke-WebRequest -Method POST -Body $postParam -ContentType "application/x-www-form-urlencoded; charset=utf-8" -Uri http://localhost:8888/api/Send

 

ContentType은 저의 경우 Form 방식을 이용했기 때문에 application/x-www-form-urlencoded 를 이용했습니다.

JSON 방식이라면 application/json 으로 보내시면 됩니다.

 

 

 

 

 

 

 

 

 

728x90