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

Python 3.6.5发送带请求体的HTTP POST请求及读取响应求助(入门30分钟)

完善带XML请求体的HTTP POST请求代码

Hey there! Let's get your HTTP POST request sorted out—even with only 30 minutes of Python under your belt, this is totally doable. I'll walk you through fixing and completing your code step by step.

问题分析

Your original code was on the right track, but it was missing two key pieces:

  • Passing the XML request body along with the POST request
  • Setting the correct request headers so the server understands the data you're sending

完善后的完整代码

Here's the polished version that works with Python 3.6.5 on Windows 10:

import http.client
import xml.dom.minidom

HOST = "www.mysite.com"
API_URL = "/service"

def do_request(xml_location):
    try:
        # 安全读取XML文件内容(用with自动关闭文件)
        with open(xml_location, "r") as xml_file:
            request_body = xml_file.read()
        
        # 建立与目标服务器的HTTP连接
        webservice = http.client.HTTPConnection(HOST)
        
        # 设置请求头:告诉服务器我们发送的是XML格式数据
        headers = {
            "Content-Type": "application/xml",
            "Content-Length": str(len(request_body))  # 部分服务器要求这个字段,可选但推荐
        }
        
        # 发送POST请求,带上请求体和请求头
        webservice.request("POST", API_URL, body=request_body, headers=headers)
        
        # 获取服务器响应
        response = webservice.getresponse()
        
        # 读取并解码响应内容(转成字符串方便查看)
        response_data = response.read().decode("utf-8")
        
        # 打印响应状态和内容,方便调试
        print(f"Response Status: {response.status} {response.reason}")
        print("Response Content:")
        print(response_data)
        
        # (可选)如果需要解析XML响应,可以用xml.dom.minidom
        # parsed_response = xml.dom.minidom.parseString(response_data)
        # print("Formatted XML Response:")
        # print(parsed_response.toprettyxml())
        
        # 关闭连接
        webservice.close()
        
        return response_data
    except Exception as e:
        # 捕获并打印异常,避免程序崩溃
        print(f"Oops, something went wrong: {str(e)}")
        return None

# 调用函数,替换成你的XML文件实际路径
do_request("C:/path/to/your/request.xml")

关键步骤解释

Let's break down the important parts so you understand what's happening:

  • with open(...): This is a safer way to read files in Python—it automatically closes the file after reading, so you don't have to remember to do it manually.
  • Request Headers: The Content-Type header tells the server "this is XML data", which is crucial for it to process your request correctly. Content-Length helps the server know how much data to expect.
  • Sending the Request: The request() method takes the HTTP method (POST), URL, request body, and headers all in one go—this is simpler than splitting it into putheader/endheaders calls (though that works too if you prefer).
  • Reading the Response: getresponse() fetches the server's reply, read() gets the raw bytes, and decode("utf-8") converts those bytes into a human-readable string.
  • Exception Handling: The try/except block catches common errors like missing files or failed connections, so your script doesn't crash unexpectedly.

If you need to use HTTPS instead of HTTP, just replace http.client.HTTPConnection with http.client.HTTPSConnection—the rest of the code stays almost the same!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:12:42