如何使用python xmlrpclib发送自定义http头进行RPC调用?

5 投票
1 回答
3342 浏览
提问于 2025-04-16 09:33

我该如何使用Python的xmlrpclib库发送自定义的HTTP Headers呢?在调用RPC方法时,我需要发送一些特别的自定义http_headers

1 个回答

15

你可以创建一个新的类,继承自 xmlrpclib.Transport,然后把这个新类作为参数传给 ServerProxy。选择一个你想要重写的方法(我选择了 send_content),这样就可以了。

# simple test program (from the XML-RPC specification)
from xmlrpclib import ServerProxy, Transport, Error

class SpecialTransport(Transport):

    def send_content(self, connection, request_body):

        print "Add your headers here!"

        connection.putheader("Content-Type", "text/xml")
        connection.putheader("Content-Length", str(len(request_body)))
        connection.endheaders()
        if request_body:
            connection.send(request_body)


# server = ServerProxy("http://localhost:8000") # local server
server = ServerProxy("http://betty.userland.com", transport=SpecialTransport())

print server

try:
    print server.examples.getStateName(41)
except Error, v:
    print "ERROR", v

撰写回答