HTTP 메서드 및 데이터 전송
curl은 기본 GET 메서드 외에도 다양한 HTTP 메서드를 지원합니다. 이 단계에서는 다양한 HTTP 메서드를 사용하고 요청과 함께 데이터를 전송하는 방법을 배우게 됩니다.
POST 메서드 사용
POST 메서드는 일반적으로 서버에 데이터를 제출하는 데 사용됩니다. -X 옵션을 사용하여 HTTP 메서드를 지정하고 -d 옵션을 사용하여 데이터를 제공할 수 있습니다. 시도해 보겠습니다.
curl -X POST -d "name=John&age=25" https://httpbin.org/post
이 명령은 httpbin.org 에 폼 데이터와 함께 POST 요청을 보냅니다. 응답은 보낸 데이터를 다시 에코해야 합니다.
{
"args": {},
"data": "",
"files": {},
"form": {
"age": "25",
"name": "John"
},
"headers": {
"Accept": "*/*",
"Content-Length": "16",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "curl/7.81.0",
"X-Amzn-Trace-Id": "Root=1-65b..."
},
"json": null,
"origin": "your-ip-address",
"url": "https://httpbin.org/post"
}
JSON 데이터 전송
JSON 데이터를 전송하려면 Content-Type 헤더를 지정해야 합니다. 다음을 실행합니다.
curl -X POST -H "Content-Type: application/json" -d '{"name":"John","age":25}' https://httpbin.org/post
응답에는 JSON 데이터가 포함되어야 합니다.
{
"args": {},
"data": "{\"name\":\"John\",\"age\":25}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Content-Length": "24",
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "curl/7.81.0",
"X-Amzn-Trace-Id": "Root=1-65b..."
},
"json": {
"age": 25,
"name": "John"
},
"origin": "your-ip-address",
"url": "https://httpbin.org/post"
}
다른 HTTP 메서드 사용
curl은 모든 표준 HTTP 메서드를 지원합니다. PUT 요청을 시도해 보겠습니다.
curl -X PUT -d "data=example" https://httpbin.org/put
DELETE 요청도 시도할 수 있습니다.
curl -X DELETE https://httpbin.org/delete
각 명령은 요청의 세부 정보를 보여주는 응답을 반환합니다.
POST 요청의 출력을 파일에 저장해 보겠습니다.
curl -X POST -d "name=John&age=25" -o data/post_response.json https://httpbin.org/post
파일이 생성되었는지 확인합니다.
ls -l data/post_response.json
그리고 내용을 확인합니다.
cat data/post_response.json
이전에 표시된 것과 유사한 httpbin.org 의 JSON 응답을 볼 수 있습니다.