问题使用Python

时间:2015-09-17 10:51:56

标签: python soap python-requests

我正在尝试访问NJTransit API,我已成功使用Postman应用程序查询它,但无论我尝试什么,我都无法让python成功返回所需的查询。 使用suds:

from suds.client import Client
url = "http://traindata.njtransit.com:8090/NJTTrainData.asmx?wsdl"
client = Client(url, cache = None)
from suds.sax.element import Element
auth = Element('UserCredentials')
auth.append(Element('userName').setText(my_username))
auth.append(Element('password').setText(my_password))
client.set_options(soapheaders = auth)
client = Client(url, cache = None)
result = client.service.getTrainScheduleJSON("NY")

这导致“无”。

我还尝试使用Postman应用程序建议的预先格式化的请求,但是我一直收到404错误。

import requests

url = "http://traindata.njtransit.com:8090/NJTTrainData.asmx"

querystring = {"wsdl":""}

payload = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n  <soap:Header>\n    <UserCredentials xmlns=\"http://microsoft.com/webservices/\">\n      <userName>---</userName>\n      <password>---</password>\n    </UserCredentials>\n  </soap:Header>\n  <soap:Body>\n      <getTrainScheduleJSON xmlns=\"http://microsoft.com/webservices/\">\n      <station>NY</station>\n    </getTrainScheduleJSON>\n  </soap:Body>\n</soap:Envelope>"
headers = {
    'content-type': "text/xml; charset=utf-8",
    'host': "traindata.njtransit.com",
    'soapaction': "http//microsoft.com/webservices/getTrainScheduleJSON"
    }

response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

print(response.text)

我非常感谢任何帮助/见解。

1 个答案:

答案 0 :(得分:0)

你永远不想设置&#34;主机&#34;标题,这将由请求完成。

404由错误的SOAPAction触发。有一个缺失:在http之后。

以下代码段对我来说很好。

import requests

url = "http://traindata.njtransit.com:8090/NJTTrainData.asmx"

querystring = {"wsdl":""}

payload = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n  <soap:Header>\n    <UserCredentials xmlns=\"http://microsoft.com/webservices/\">\n      <userName>---</userName>\n      <password>---</password>\n    </UserCredentials>\n  </soap:Header>\n  <soap:Body>\n      <getTrainScheduleJSON xmlns=\"http://microsoft.com/webservices/\">\n      <station>NY</station>\n    </getTrainScheduleJSON>\n  </soap:Body>\n</soap:Envelope>"
headers = {
    'content-type': "text/xml; charset=utf-8",
    'soapaction': 'http://microsoft.com/webservices/getTrainScheduleJSON'
}

response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

print response
print(response.text)