curl - Cliente HTTP y Transferencia de Datos¶
Comandos curl completos para solicitudes HTTP, pruebas de API y transferencia de datos en todas las plataformas.
Solicitudes HTTP Básicas¶
Solicitudes GET¶
| Comando | Descripción |
|---|---|
curl https://api.example.com |
Solicitud GET básica |
curl -v https://api.example.com |
Salida detallada con encabezados |
curl -i https://api.example.com |
Incluir encabezados de respuesta |
curl -I https://api.example.com |
Solicitud HEAD únicamente |
curl -L https://example.com |
Seguir redirects |
| ### Solicitudes POST | |
| Comando | Descripción |
| --------- | ------------- |
curl -X POST https://api.example.com |
Solicitud POST básica |
curl -d "data" https://api.example.com |
POST con datos |
curl -d @file.json https://api.example.com |
Datos POST desde archivo |
curl -F "file=@upload.txt" https://api.example.com |
Carga de archivo |
| ### Otros Métodos HTTP | |
| Comando | Descripción |
| --------- | ------------- |
curl -X PUT -d "data" https://api.example.com |
Solicitud PUT |
curl -X DELETE https://api.example.com/item/1 |
Solicitud DELETE |
curl -X PATCH -d "data" https://api.example.com |
Solicitud PATCH |
| ## Encabezados y Autenticación |
Encabezados Personalizados¶
| Comando | Descripción |
|---|---|
curl -H "Content-Type: application/json" url |
Establecer tipo de contenido |
curl -H "Authorization: Bearer token" url |
Autenticación de token Bearer |
curl -H "User-Agent: MyApp/1.0" url |
Agente de usuario personalizado |
curl -H "Accept: application/xml" url |
Encabezado Accept |
| ### Métodos de Autenticación | |
| Comando | Descripción |
| --------- | ------------- |
curl -u username:password url |
Autenticación básica |
curl -u username url |
Solicitar contraseña |
curl --oauth2-bearer token url |
Token de portador OAuth2 |
curl --digest -u user:pass url |
Autenticación Digest |
| ### Autenticación con Clave API | |
Formatos de Datos¶
Datos 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
Datos de Formulario¶
# 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
Datos 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
Operaciones con Archivos¶
Descargar Archivos¶
| Comando | Descripción |
|---|---|
curl -O https://example.com/file.zip |
Descargar con nombre original |
curl -o myfile.zip https://example.com/file.zip |
Descargar con nombre personalizado |
curl -C - -O https://example.com/file.zip |
Reanudar descarga interrumpida |
curl --limit-rate 100k -O url |
Limitar velocidad de descarga |
| ### Subir Archivos | |
| Comando | Descripción |
| --------- | ------------- |
curl -T file.txt ftp://server/path/ |
Cargar mediante FTP |
curl -F "file=@upload.txt" url |
Carga de archivos HTTP |
curl --upload-file file.txt url |
Subir archivo PUT |
| ### Múltiples Archivos | |
Opciones Avanzadas¶
Timeouts y Reintentos¶
| Comando | Descripción |
|---|---|
curl --connect-timeout 10 url |
Tiempo de espera de conexión (segundos) |
curl --max-time 30 url |
Tiempo total máximo |
curl --retry 3 url |
Reintentar en caso de fallo |
curl --retry-delay 5 url |
Intervalo entre reintentos |
| ### Opciones SSL/TLS | |
| Comando | Descripción |
| --------- | ------------- |
curl -k url |
Ignorar errores de certificado SSL |
curl --cacert ca.pem url |
Usar certificado de CA personalizado |
curl --cert client.pem url |
Usar certificado de cliente |
curl --tlsv1.2 url |
Forzar versión TLS |
| ### Proxy y Red | |
| Comando | Descripción |
| --------- | ------------- |
curl --proxy proxy.example.com:8080 url |
Usar proxy HTTP |
curl --socks5 proxy.example.com:1080 url |
Usar proxy SOCKS5 |
curl --interface eth0 url |
Utilizar interfaz de red específica |
curl --dns-servers 8.8.8.8 url |
Usar servidores DNS personalizados |
| ## Salida y Formato |
Control de Salida¶
Procesamiento 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)'
Pruebas y Depuración¶
Pruebas de API¶
Would you like me to continue with the remaining translations?```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 ```### Pruebas de Rendimiento
# 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
```### Manejo de Errores
```bash
# 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
```## Configuración y Scripts
```bash
# ~/.curlrc configuration file
user-agent = "MyApp/1.0"
connect-timeout = 10
max-time = 30
show-error
silent
```### Archivo de Configuración
```bash
#!/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"\\\\}'
```### Scripting en Bash
```bash
# 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"
```## Mejores Prácticas de Seguridad
```bash
# 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
```### Autenticación Segura
```bash
# 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
```### Verificación de Certificados
```bash
# 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
```## Casos de Uso Comunes
```bash
# 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
```### Web Scraping
| Problema | Solución |
|---------|----------|
| SSL certificate errors | Use `-k` for testing, fix certificates for production |
| Connection timeout | Increase `--connect-timeout` value |
| Slow downloads | Use `--limit-rate` to control bandwidth |
| Authentication failures | Verificar credenciales y método de autenticación |### Integración de API
```bash
# 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