You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JSON-RPC调用脚本执行后打印POST请求状态码?

Fixing the Missing Status Code Printout in Your Script

Hey there! I see your script can complete the task but isn't printing the request status code—let's get that sorted out quickly. The main issue here is that your current code defines all the necessary parameters, but it doesn't actually send the HTTP request or access the status code from the response.

Here's the updated version of your script with the missing pieces added, plus some error handling to make it more robust:

import requests
import json

url = 'http://10.3.198.100/ins'
switchuser = 'user'
switchpassword = 'password'
myheaders = {'content-type' : 'application/json-rpc'}
payload = [
    {
        "jsonrpc": "2.0",
        "method": "cli",
        "params": {
            "cmd": "vrf context management",
            "version": 1
        },
        "id": 1
    },
    # Add your remaining payload objects here
    {
        "jsonrpc": "2.0",
        # Your other method/parameter details go here
    }
]

try:
    # Send the POST request with authentication and JSON payload
    response = requests.post(
        url,
        data=json.dumps(payload),
        headers=myheaders,
        auth=(switchuser, switchpassword)
    )

    # Print the HTTP status code
    print(f"Request Status Code: {response.status_code}")

    # Optional: Uncomment below to see the full response content
    # print("Full Response:", json.dumps(response.json(), indent=2))

except requests.exceptions.RequestException as e:
    # Catch and print any request errors (connection issues, timeouts, etc.)
    print(f"Request failed with error: {e}")

Key Changes Explained:

  • Sending the Request: The requests.post() call is the missing piece—it sends your payload to the device's API endpoint, using the authentication credentials you defined. We use json.dumps(payload) to convert your Python list into a JSON string, which matches the application/json-rpc content type in your headers.
  • Accessing the Status Code: response.status_code gives you the HTTP status code directly. Common codes you might see:
    • 200: Request succeeded
    • 401: Authentication failed (check your username/password)
    • 500: Server-side error on the network device
  • Error Handling: The try-except block catches common request issues (like failed connections or timeouts) so your script doesn't crash unexpectedly, and gives you a clear error message.

Just fill in the rest of your payload objects, run the script, and you'll see the status code printed out every time!

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:48:49