如何使用Python的requests向WCF发送复杂类型?
我正在尝试用Python的requests库来查询一个WCF网络服务。
我按照Visual Studio的默认模板创建了一个非常简单的WCF网络服务:
[ServiceContract]
public interface IHWService
{
[OperationContract]
[WebInvoke(Method="GET", UriTemplate="SayHello", ResponseFormat=WebMessageFormat.Json)]
string SayHello();
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "GetData", ResponseFormat = WebMessageFormat.Json)]
string GetData(int value);
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "GetData2", BodyStyle=WebMessageBodyStyle.Bare, RequestFormat=WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
从Python中,我成功调用了前两个接口,并且很容易得到了数据。
但是,我想调用第三个接口,它涉及到复杂类型的概念。
这是我的Python代码:
import requests as req
import json
wsAddr="http://localhost:58356/HWService.svc"
methodPath="/GetData2"
cType={'BoolValue':"true", 'StringValue':'Hello world'}
headers = {'content-type': 'application/json'}
result=req.post(wsAddr+methodPath,params=json.dumps({'composite':json.dumps(cType)}),headers=headers)
但是它没有工作,也就是说,如果我在Visual Studio的GetDataUsingDataContract
方法中设置断点,我会发现composite
参数是null
。我觉得这可能是解析时出现了问题,但我不太清楚哪里出了错。
你能看到明显的错误吗?
你知道我怎么能在解析机制中调试吗?
编辑:
这是复杂类型的定义:
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
1 个回答
1
你需要把JSON数据放在POST请求的主体中,但你却把它放在了查询参数里。
应该使用data
,并且只对外层结构进行编码:
result=req.post(wsAddr+methodPath,
data=json.dumps({'composite': cType}),
headers=headers)
如果你对cType
进行了编码,那么你发送的就是一个包含另一个JSON编码字符串的JSON编码字符串,而这个字符串里面又包含了你的cType
字典。