Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import requests
- import json
- import textwrap
- def analyze_network_request(url_awal: str):
- """
- Melakukan request HTTP ke URL, melacak seluruh rantai redirect (history),
- dan menampilkan detail Request/Response Headers serta Payload (JSON/Text)
- untuk setiap langkah, menyerupai Developer Tools.
- """
- print("=========================================================================")
- print(f"š Memulai Analisis Jaringan GET ke: {url_awal}")
- print("=========================================================================")
- try:
- # Lakukan request, biarkan requests mengikuti redirect secara otomatis
- response = requests.get(url_awal, timeout=15)
- # Gabungkan objek riwayat dengan objek respons akhir untuk iterasi penuh
- all_responses = response.history + [response]
- for i, resp in enumerate(all_responses):
- is_final = (i == len(all_responses) - 1)
- # --- Judul Langkah ---
- if is_final:
- print("\n\n#########################################################################")
- print(f"š RESPON AKHIR (Final URL)")
- print("#########################################################################")
- else:
- print("\n-------------------------------------------------------------------------")
- print(f"ā”ļø LANGKAH {i+1} - REDIRECT ({resp.status_code})")
- print("-------------------------------------------------------------------------")
- # 1. TAMPILAN REQUEST HEADERS
- print(f"1. REQUEST HEADERS ({resp.request.method}):")
- print(f" URL: {resp.url}")
- for header, value in resp.request.headers.items():
- print(f" > {header}: {value}")
- # Request Body (Payload) - Biasanya N/A untuk GET
- request_body = resp.request.body if resp.request.body else 'N/A (No Body)'
- if request_body != 'N/A (No Body)':
- print(f" Body: {request_body}")
- # 2. TAMPILAN RESPONSE HEADERS
- print(f"\n2. RESPONSE HEADERS (Status: {resp.status_code}):")
- for header, value in resp.headers.items():
- if not is_final and header.lower() == 'location':
- # Highlight Location header untuk langkah redirect
- print(f" >> **{header}: {value}**")
- else:
- print(f" > {header}: {value}")
- # 3. TAMPILAN RESPONSE PAYLOAD (Hanya di langkah akhir)
- if is_final:
- print("\n3. RESPONSE PAYLOAD (Body):")
- # Cek Content-Type untuk petunjuk
- content_type = resp.headers.get('Content-Type', '').lower()
- try:
- # š„ Prioritas #1: Coba parsing sebagai JSON (untuk Ajax)
- data_json = resp.json()
- # Konfirmasi Tipe
- if 'application/json' in content_type:
- print(" [TIPE: JSON (Ajax) - Confirmed by Header]")
- else:
- print(" [TIPE: JSON (Ajax) - Parsing Berhasil]")
- # Format JSON yang rapi
- formatted_json = json.dumps(data_json, indent=2)
- # Tampilkan hingga 1000 karakter pertama
- print(textwrap.indent(formatted_json[:1000] + ('...' if len(formatted_json) > 1000 else ''), ' '))
- except (json.JSONDecodeError, UnicodeDecodeError):
- # š„ Prioritas #2: Jika gagal, tampilkan sebagai Teks/HTML
- print(" [TIPE: Text/HTML/Other - Gagal Parsing JSON]")
- text_snippet = resp.text
- # Tampilkan hingga 500 karakter pertama
- print(textwrap.indent(text_snippet[:500] + ('...' if len(text_snippet) > 500 else ''), ' '))
- except requests.exceptions.RequestException as e:
- print(f"\nā Terjadi kesalahan saat melakukan request: {e}")
- finally:
- print("\n=========================================================================")
- # --- CARA MENGGUNAKAN (WORKING EXAMPLE) ---
- # Gunakan URL API (JSON) untuk melihat Payload JSON
- # url_to_test = "https://jsonplaceholder.typicode.com/todos/1"
- # Gunakan URL web (HTML + Redirect Chain) untuk melihat Redirect History
- url_to_test = "http://www.cisco.com"
- # Jalankan fungsi
- analyze_network_request(url_to_test)
Advertisement
Add Comment
Please, Sign In to add comment