Zum Inhalt springen

xh - Moderner HTTP Client Spickzettel

xh - Moderner HTTP Client Spickzettel

Installation

PlattformBefehl
Ubuntu/Debian`curl -sfL https://raw.githubusercontent.com/ducaale/xh/master/install.sh \
Arch Linuxpacman -S xh
Fedora/RHELdnf install xh
macOS (Homebrew)brew install xh
macOS (MacPorts)sudo port install xh
Windows (Scoop)scoop install xh
Windows (Chocolatey)choco install xh
Cargo (All platforms)cargo install xh
Dockerdocker pull ducaale/xh
Snapsnap install xh

Grundlegende Befehle

BefehlBeschreibung
xh httpbin.org/getEinfache GET-Anfrage
xh POST httpbin.org/post name=JohnPOST-Anfrage mit JSON-Daten
xh PUT httpbin.org/put status=activePUT-Anfrage mit Daten
xh PATCH httpbin.org/patch email=new@email.comPATCH-Anfrage zum Aktualisieren einer Ressource
xh DELETE httpbin.org/deleteDELETE-Anfrage
xh HEAD httpbin.org/getHEAD-Anfrage (nur Header)
xh OPTIONS httpbin.org/getOPTIONS-Anfrage
xh httpbin.org/get search==rustGET mit Abfrageparameter
xh httpbin.org/get page==1 limit==10Mehrere Abfrageparameter
xh -a user:pass httpbin.org/basic-auth/user/passBasis-Authentifizierung
xh -A bearer -a token123 api.example.comBearer-Token-Authentifizierung
xh httpbin.org/get User-Agent:CustomAgentBenutzerdefinierter Header
xh -b httpbin.org/jsonNur Antworttext ausgeben
xh -h httpbin.org/jsonNur Antwortheader ausgeben
xh -v httpbin.org/jsonAusführliche Ausgabe (Header + Body)
xh httpbin.org/json -o response.jsonDownload-Antwort in Datei
xh --follow=0 httpbin.org/redirect/3Folgen Sie keine Weiterleitungen
xh -f POST httpbin.org/post name=JohnPOST mit Formulardaten
xh POST httpbin.org/post < data.jsonPOST mit Dateiinhalt
xh httpbin.org/get Authorization:"Bearer token"Authorization-Header

Erweiterte Nutzung

BefehlBeschreibung
xh POST httpbin.org/post age:=30 active:=trueJSON mit Typumwandlung (Zahl/Boolean)
xh POST httpbin.org/post tags:='["rust","cli"]'JSON-Array senden
xh POST httpbin.org/post user[name]=John user[age]:=30Verschachtelte JSON-Objekte
xh --session=mysession httpbin.org/cookies/set/token/abcBenannte Sitzung erstellen (Cookies speichern)
xh --session=mysession httpbin.org/cookiesSession wiederverwenden
xh --session-read-only=mysession httpbin.org/getSession ohne Aktualisierung verwenden
xh -f POST httpbin.org/post file@/path/to/file.txtDatei als Multipart-Formular hochladen
xh POST httpbin.org/post @file.jsonDatei als Anforderungstext hochladen
xh --proxy=http:http://proxy.example.com:8080 httpbin.org/getHTTP-Proxy verwenden
xh --proxy=all:socks5://localhost:1080 httpbin.org/getSOCKS5-Proxy verwenden
xh --verify=no https://self-signed.badssl.com/SSL-Überprüfung überspringen (unsicher)
xh --cert=/path/to/ca-cert.pem https://api.example.comBenutzerdefiniertes CA-Zertifikat
xh --cert=/path/to/client.crt --cert-key=/path/to/client.key https://api.example.comClient-Zertifikatsauthentifizierung
xh --timeout=30 httpbin.org/delay/5Anforderungs-Timeout (Sekunden) festlegen
xh --pretty=none httpbin.org/jsonFarbige/formatierte Ausgabe deaktivieren
xh --style=monokai httpbin.org/jsonVerwende ein spezifisches Farbschema
xh --stream httpbin.org/stream/100Stream-Antwort
xh --download httpbin.org/image/png -o image.pngDownload mit Fortschrittsbalken
xh --continue httpbin.org/stream/100 -o stream.txtDownload-Fortsetzung
xh --http-version=1.1 https://httpbin.org/getErzwinge HTTP/1.1
xh --method=CUSTOM httpbin.org/anythingBenutzerdefinierte HTTP-Methode
xh --multipart POST httpbin.org/post name=John file@doc.pdfMultipart-Formular mit gemischten Daten
xh httpbin.org/get Cookie:session=abc123Sende Cookies
xh --auth-type=digest -a user:pass httpbin.org/digest-auth/auth/user/passDigest-Authentifizierung

JSON-Datentypen

Bei der Übertragung von JSON-Daten unterstützt xh Typumwandlung mit spezieller Syntax:

SyntaxTypBeispiel
key=valueStringname=John{"name":"John"}
key:=numberNummerage:=30{"age":30}
key:=trueBooleanactive:=true{"active":true}
key:=nullNullmiddle:=null{"middle":null}
key:='[...]'Arraytags:='["a","b"]'{"tags":["a","b"]}
key:='{...}'Objektmeta:='{"v":1}'{"meta":{"v":1}}
key[sub]=valueVerschachteltuser[name]=John{"user":{"name":"John"}}

Konfiguration

Speicherorte für Sitzungen

# Linux/macOS
~/.config/xh/sessions/

# Windows
%APPDATA%\xh\sessions\

Umgebungsvariablen

# Set default proxy
export HTTP_PROXY=http://proxy.example.com:8080
export HTTPS_PROXY=http://proxy.example.com:8080

# Disable proxy for specific hosts
export NO_PROXY=localhost,127.0.0.1,.example.com

# Default timeout
export XH_TIMEOUT=30

Häufige Aliase

# Add to ~/.bashrc or ~/.zshrc

# HTTPie compatibility
alias http='xh'
alias https='xh --default-scheme=https'

# Quick shortcuts
alias xhj='xh --pretty=all'  # Force JSON pretty-print
alias xhn='xh --pretty=none' # No formatting
alias xhv='xh -v'            # Verbose by default
alias xhd='xh --download'    # Download mode

Häufige Anwendungsfälle

Anwendungsfall: REST-API-Test mit Authentifizierung

# Login and save session
xh --session=api POST https://api.example.com/login \
  username=admin password=secret

# Make authenticated requests using saved session
xh --session=api GET https://api.example.com/users

# Update resource
xh --session=api PUT https://api.example.com/users/123 \
  name="John Doe" email=john@example.com status=active

# Delete resource
xh --session=api DELETE https://api.example.com/users/123

Anwendungsfall: Datei-Upload mit Metadaten

# Upload file with additional form fields
xh -f POST https://api.example.com/upload \
  file@/path/to/document.pdf \
  title="Important Document" \
  category=legal \
  tags:='["contract","2024"]'

# Multiple file upload
xh -f POST https://api.example.com/batch-upload \
  file1@image1.jpg \
  file2@image2.jpg \
  album="Vacation 2024"

Anwendungsfall: API-Test mit verschiedenen Umgebungen

# Development environment
xh --session=dev POST https://dev-api.example.com/test \
  Authorization:"Bearer dev-token-123" \
  data=test

# Staging environment
xh --session=staging POST https://staging-api.example.com/test \
  Authorization:"Bearer staging-token-456" \
  data=test

# Production environment (with SSL verification)
xh --session=prod POST https://api.example.com/test \
  Authorization:"Bearer prod-token-789" \
  data=test

Anwendungsfall: Debugging von Webhook-Payloads

# Capture webhook payload to file
xh POST https://webhook.site/your-unique-url \
  event=user.created \
  user[id]:=12345 \
  user[email]=new@example.com \
  timestamp:=$(date +%s) \
  -v -o webhook-debug.txt

# Test webhook with retry logic (in script)
for i in {1..3}; do
  xh POST https://your-app.com/webhook \
    event=test \
    attempt:=$i && break || sleep 5
done

Anwendungsfall: Herunterladen und Verarbeiten von API-Daten

# Download JSON data
xh GET https://api.github.com/users/octocat/repos \
  -o repos.json

# Download with authentication and save
xh -a token:ghp_your_token \
  GET https://api.github.com/user/repos \
  visibility==private \
  -o private-repos.json

# Stream large dataset
xh --stream GET https://api.example.com/export/data \
  format==json \
  | jq '.[] | select(.active == true)' \
  > active-records.json

Best Practices

  • Sitzungen für authentifizierte Workflows verwenden: Sitzungen speichern Cookies und Header und eliminieren die Notwendigkeit, sich für jeden Request neu zu authentifizieren. Verwenden Sie --session=namefür mehrstufige API-Interaktionen.

  • Typumwandlung für JSON nutzen: Verwenden Sie :=für Zahlen und Booleans (age:=30, active:=true) anstelle von Zeichenkettenwerten, um korrekte JSON-Typen in API-Anfragen sicherzustellen.

  • xh gegenüber curl für API-Tests bevorzugen: Die intuitive Syntax (xh POST api.com name=value) ist lesbarer als curls ausführliche Flags, was es ideal für Dokumentation und schnelle Tests macht.

  • Verbose-Modus zum Debugging verwenden: Fügen Sie -vhinzu, um vollständige Request- und Response-Header zu sehen, wenn API-Probleme oder Authentifizierungsprobleme behoben werden sollen.

  • Sensible Token in Umgebungsvariablen speichern: Anstatt von

Note: Some placeholders (15-20) are left untranslated as they seem to be specific code/command references that would typically remain in English.xh -a token:secret_key, verwendenxh -a token:$API_TOKEN, um Anmeldeinformationen in der Shell-Verlauf zu vermeiden.

  • Nutzen Sie Ausgabeumleitung für Automatisierung: Speichern Sie Antworten mit -o file.jsonzur Verarbeitung oder zum Vergleich in CI/CD-Pipelines und automatisierten Testskripten.

  • Setzen Sie geeignete Timeouts: Verwenden Sie --timeout=30für langsame APIs, um hängende Anfragen zu verhindern. Setzen Sie --timeout=0nur für Streaming- oder Langzeitoperationen.

  • Organisieren Sie Sitzungen nach Umgebung: Erstellen Sie separate Sitzungen für Entwicklung, Staging und Produktion (--session=prod-api), um versehentliche Verwendung falscher Anmeldeinformationen zu vermeiden.

Fehlerbehebung

ProblemLösung
SSL certificate verification failedUse --verify=no to skip verification (insecure) or --cert=/path/to/ca.pem to provide custom CA certificate
Connection timeoutIncrease timeout with --timeout=60 or check network connectivity and proxy settings
401 UnauthorizedVerify authentication method: use -a user:pass for basic auth, -A bearer -a token for bearer tokens, or check session validity
JSON parsing errorEnsure proper syntax: use := for non-strings (age:=30), quote arrays (tags:='["a","b"]'), and check for unescaped special characters
Command not found: xhVerify installation path is in $PATH, reinstall using preferred method, or use full path /usr/local/bin/xh
Session not persistingCheck session directory permissions (~/.config/xh/sessions/), ensure using same session name, verify not using --session-read-only
Proxy connection failedVerify proxy URL format --proxy=http:http://host:port, check proxy authentication if required, ensure proxy allows target host
File upload failsUse -f or --multipart flag for form uploads, verify file path is correct, check file permissions and size limits
Response not formatted/coloredForce formatting with --pretty=all, check terminal supports colors, or pipe through jq for JSON formatting