반응형
curl은 HTTP 요청을 보내고 응답을 확인할 수 있는 명령어 기반 도구입니다.
주로 API 테스트, 파일 다운로드, 데이터 전송 등에 사용됩니다.
✅ 1. 기본 사용법
curl <옵션> <URL>
🔹 GET 요청 (기본 요청)
curl https://example.com
👉 기본적으로 GET 요청을 보내며, 웹페이지나 API 응답을 가져올 수 있음.
✅ 2. HTTP 요청 보내기
🔹 2.1 GET 요청
curl -X GET https://api.example.com/users
- -X GET을 명시할 필요 없이 URL만 입력해도 기본적으로 GET 요청을 보냄.
🔹 2.2 POST 요청 (데이터 전송)
curl -X POST https://api.example.com/login -d "username=admin&password=1234"
- -X POST : POST 요청을 보냄
- -d "데이터" : 서버에 전송할 데이터(body 내용) 추가
📌 JSON 데이터 전송 (POST)
curl -X POST https://api.example.com/login \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "1234"}'
- -H "Content-Type: application/json" : JSON 형식으로 요청 보냄
- -d '{"key": "value"}' : JSON 데이터를 직접 body에 포함
🔹 2.3 PUT 요청 (데이터 수정)
curl -X PUT https://api.example.com/users/1 \
-H "Content-Type: application/json" \
-d '{"name": "John Doe", "email": "john@example.com"}'
👉 ID가 1인 사용자의 정보(name, email)를 수정
🔹 2.4 DELETE 요청 (데이터 삭제)
curl -X DELETE https://api.example.com/users/1
👉 ID가 1인 사용자 삭제
✅ 3. 헤더(Header) 추가하기
🔹 인증 토큰 추가 (Authorization)
curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" https://api.example.com/data
- -H "Authorization: Bearer <토큰>" : JWT, OAuth 토큰 등 인증 헤더 추가
🔹 여러 개의 헤더 추가
curl -H "Accept: application/json" \
-H "User-Agent: MyApp/1.0" \
https://api.example.com/data
- Accept: application/json : JSON 응답을 요청
- User-Agent: MyApp/1.0 : 사용자 지정 User-Agent 지정
✅ 4. 응답 결과 저장하기
🔹 응답을 파일로 저장
curl -o output.html https://example.com
- -o output.html : 응답을 output.html 파일로 저장
📌 자동 파일 이름 저장
curl -O https://example.com/file.zip
- -O 옵션을 사용하면 URL의 파일 이름 그대로 저장됨 (ex: file.zip)
✅ 5. 추가 기능
🔹 리디렉션(redirect) 따라가기
curl -L https://short.url
- -L : URL이 리디렉션될 경우 자동으로 따라감
🔹 응답 헤더만 보기
curl -I https://example.com
- -I : 응답 헤더만 가져오기 (HEAD 요청)
- 출력 예시:
HTTP/1.1 200 OK Date: Tue, 13 Feb 2025 10:00:00 GMT Content-Type: text/html; charset=UTF-8
🔹 응답 내용 & 헤더 같이 보기
curl -v https://example.com
- -v : 요청과 응답 과정 전체(Verbose) 출력
🔹 cURL 요청 로그 저장
curl -v -o response.txt https://api.example.com/data
- -v : 요청 과정 로그 보기
- -o response.txt : 응답 내용을 response.txt에 저장
✅ 6. REST API 테스트 예제
📌 JSON 데이터 포함하여 POST 요청
curl -X POST https://api.example.com/user \
-H "Content-Type: application/json" \
-d '{"name": "Alice", "age": 25}'
📌 JWT 인증 추가 후 GET 요청
curl -H "Authorization: Bearer my-jwt-token" https://api.example.com/protected
🚀 결론
기능명령어 예시
GET 요청 | curl https://example.com |
POST 요청 | curl -X POST -d "name=John" https://api.example.com |
JSON 데이터 POST | curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' https://api.com |
헤더 추가 | curl -H "Authorization: Bearer TOKEN" https://api.com |
응답 저장 | curl -o file.html https://example.com |
응답 헤더만 보기 | curl -I https://example.com |
리디렉션 따라가기 | curl -L https://short.url |
이제 curl을 사용하여 API 요청, 파일 다운로드, 인증 테스트 등을 쉽게 수행할 수 있습니다! 🚀
반응형