콘텐츠로 이동

curl - HTTP 클라이언트 및 데이터 전송

모든 플랫폼에서 HTTP 요청, API 테스트 및 데이터 전송을 위한 포괄적인 curl 명령어.

기본 HTTP 요청

GET 요청

명령어설명
curl https://api.example.com기본 GET 요청
curl -v https://api.example.com헤더와 함께 상세 출력
curl -i https://api.example.com응답 헤더 포함
curl -I https://api.example.comHEAD 요청만
curl -L https://example.com리다이렉트 따라가기

POST 요청

명령어설명
curl -X POST https://api.example.com기본 POST 요청
curl -d "data" https://api.example.com데이터와 함께 POST
curl -d @file.json https://api.example.com파일에서 POST 데이터
curl -F "file=@upload.txt" https://api.example.com파일 업로드

기타 HTTP 메서드

명령어설명
curl -X PUT -d "data" https://api.example.comPUT 요청
curl -X DELETE https://api.example.com/item/1DELETE 요청
curl -X PATCH -d "data" https://api.example.comPATCH 요청

헤더 및 인증

사용자 정의 헤더

명령어설명
curl -H "Content-Type: application/json" url콘텐츠 유형 설정
curl -H "Authorization: Bearer token" url베어러 토큰 인증
curl -H "User-Agent: MyApp/1.0" url사용자 지정 사용자 에이전트
curl -H "Accept: application/xml" urlAccept 헤더

인증 방법

명령어설명
curl -u username:password url기본 인증
curl -u username url비밀번호를 입력하세요
curl --oauth2-bearer token urlOAuth2 베어러 토큰
curl --digest -u user:pass url다이제스트 인증

API 키 인증

# API key in header
curl -H "X-API-Key: your-api-key" https://api.example.com

# API key in query parameter
curl "https://api.example.com?api_key=your-api-key"

# Multiple headers
curl -H "Authorization: Bearer token" \
     -H "Content-Type: application/json" \
     https://api.example.com

데이터 형식

JSON 데이터

# POST JSON data
curl -X POST \
     -H "Content-Type: application/json" \
     -d '\\\\{"name":"John","age":30\\\\}' \
     https://api.example.com/users

# JSON from file
curl -X POST \
     -H "Content-Type: application/json" \
     -d @data.json \
     https://api.example.com/users

폼 데이터

# URL-encoded form data
curl -d "name=John&age=30" https://api.example.com/users

# Multipart form data
curl -F "name=John" -F "age=30" https://api.example.com/users

# File upload with form data
curl -F "file=@document.pdf" \
     -F "description=Important document" \
     https://api.example.com/upload

XML 데이터

# POST XML data
curl -X POST \
     -H "Content-Type: application/xml" \
     -d '<user><name>John</name><age>30</age></user>' \
     https://api.example.com/users

파일 작업

파일 다운로드

명령어설명
curl -O https://example.com/file.zip원본 이름으로 다운로드
curl -o myfile.zip https://example.com/file.zip사용자 지정 이름으로 다운로드
curl -C - -O https://example.com/file.zip다운로드 중단 재개
curl --limit-rate 100k -O url다운로드 속도 제한

파일 업로드

명령어설명
curl -T file.txt ftp://server/path/FTP를 통해 업로드
curl -F "file=@upload.txt" urlHTTP 파일 업로드
curl --upload-file file.txt urlPUT 파일 업로드

다중 파일

# Download multiple files
curl -O https://example.com/file1.zip -O https://example.com/file2.zip

# Upload multiple files
curl -F "file1=@doc1.pdf" -F "file2=@doc2.pdf" https://api.example.com/upload

고급 옵션

타임아웃 및 재시도

명령어설명
curl --connect-timeout 10 url연결 시간 초과 (초)
curl --max-time 30 url최대 총 시간
curl --retry 3 url실패 시 다시 시도
curl --retry-delay 5 url재시도 간 지연

SSL/TLS 옵션

명령어설명
curl -k urlSSL 인증서 오류 무시
curl --cacert ca.pem url사용자 지정 CA 인증서 사용
curl --cert client.pem url클라이언트 인증서 사용
curl --tlsv1.2 urlTLS 버전 강제

프록시 및 네트워크

명령어설명
curl --proxy proxy.example.com:8080 urlHTTP 프록시 사용
curl --socks5 proxy.example.com:1080 urlSOCKS5 프록시 사용
curl --interface eth0 url특정 네트워크 인터페이스 사용
curl --dns-servers 8.8.8.8 url사용자 지정 DNS 서버 사용

출력 및 포맷팅

출력 제어

명령어설명
curl -s url무음 모드 (진행 없음)
curl -S url자동 모드에서도 오류 표시하기
curl -o /dev/null url출력 폐기
curl -w "%\\{http_code\\}" urlHTTP 상태 코드만 표시

응답 정보

# Get detailed timing information
curl -w "@curl-format.txt" https://example.com

# curl-format.txt content:
#     time_namelookup:  %\\\\{time_namelookup\\\\}\n
#        time_connect:  %\\\\{time_connect\\\\}\n
#     time_appconnect:  %\\\\{time_appconnect\\\\}\n
#    time_pretransfer:  %\\\\{time_pretransfer\\\\}\n
#       time_redirect:  %\\\\{time_redirect\\\\}\n
#  time_starttransfer:  %\\\\{time_starttransfer\\\\}\n
#                     ----------\n
#          time_total:  %\\\\{time_total\\\\}\n

JSON 처리

# Pretty print JSON with jq
curl -s https://api.example.com/users|jq '.'

# Extract specific fields
curl -s https://api.example.com/users|jq '.[]|.name'

# Filter results
curl -s https://api.example.com/users|jq '.[]|select(.age > 25)'

테스트 및 디버깅

API 테스트```bash

Test REST API endpoints

curl -X GET https://api.example.com/users curl -X POST -d ’\\{“name”:“John”\\}’ https://api.example.com/users curl -X PUT -d ’\\{“name”:“Jane”\\}’ https://api.example.com/users/1 curl -X DELETE https://api.example.com/users/1

Test with different content types

curl -H “Accept: application/json” https://api.example.com/users curl -H “Accept: application/xml” https://api.example.com/users


### Performance Testing
```bash
# Measure response time
curl -w "Total time: %\\\\{time_total\\\\}s\n" -o /dev/null -s https://example.com

# Test multiple requests
for i in \\\\{1..10\\\\}; do
  curl -w "%\\\\{time_total\\\\}\n" -o /dev/null -s https://example.com
done

Error Handling

# Check HTTP status codes
http_code=$(curl -s -o /dev/null -w "%\\\\{http_code\\\\}" https://example.com)
if [ $http_code -eq 200 ]; then
    echo "Success"
else
    echo "Error: HTTP $http_code"
fi

Configuration and Scripts

Configuration File

# ~/.curlrc configuration file
user-agent = "MyApp/1.0"
connect-timeout = 10
max-time = 30
show-error
silent

Bash Scripting

#!/bin/bash
# API testing script

BASE_URL="https://api.example.com"
API_KEY="your-api-key"

# Function to make authenticated requests
api_request() \\\\{
    local method=$1
    local endpoint=$2
    local data=$3

    curl -X "$method" \
         -H "Authorization: Bearer $API_KEY" \
         -H "Content-Type: application/json" \
         $\\\\{data:+-d "$data"\\\\} \
         "$BASE_URL$endpoint"
\\\\}

# Usage examples
api_request GET "/users"
api_request POST "/users" '\\\\{"name":"John","email":"john@example.com"\\\\}'

Security Best Practices

Secure Authentication

# Use environment variables for sensitive data
export API_TOKEN="your-secret-token"
curl -H "Authorization: Bearer $API_TOKEN" https://api.example.com

# Read credentials from file
curl -K credentials.txt https://api.example.com

# credentials.txt:
# header = "Authorization: Bearer your-token"

Certificate Verification

# Always verify SSL certificates in production
curl --cacert /path/to/ca-bundle.crt https://api.example.com

# For development only (not recommended for production)
curl -k https://self-signed.example.com

Common Use Cases

Web Scraping

# Download webpage
curl -L https://example.com > page.html

# Follow redirects and save cookies
curl -L -c cookies.txt -b cookies.txt https://example.com

# Set user agent to avoid blocking
curl -H "User-Agent: Mozilla/5.0 (compatible; bot)" https://example.com

API Integration

# GitHub API example
curl -H "Authorization: token your-github-token" \
     https://api.github.com/user/repos

# Weather API example
curl "https://api.openweathermap.org/data/2.5/weather?q=London&appid=your-api-key"

# Slack webhook example
curl -X POST \
     -H "Content-Type: application/json" \
     -d '\\\\{"text":"Hello from curl!"\\\\}' \
     https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK

File Transfer

# Upload to cloud storage
curl -X PUT \
     -H "Authorization: Bearer token" \
     --upload-file document.pdf \
     https://api.storage.com/files/document.pdf

# Download with progress bar
curl --progress-bar -O https://example.com/largefile.zip

Troubleshooting

Common Issues

문제솔루션
SSL certificate errorsUse -k for testing, fix certificates for production
Connection timeoutIncrease --connect-timeout value
Slow downloadsUse --limit-rate to control bandwidth
Authentication failures자격 증명 및 인증 방법 확인

Debugging Commands

# Verbose output for debugging
curl -v https://example.com

# Trace all network activity
curl --trace trace.txt https://example.com

# Show only headers
curl -I https://example.com

# Test connectivity
curl -I --connect-timeout 5 https://example.com