从python发送一个包含JSON和非JSON数据的POST请求

时间:2015-09-24 15:30:43

标签: python json post

你如何发送一个请求(来自python),最终在网页上的实时标题中看起来像这样:http://localhost:8080):

POST /rest/marker/
json=%7B%22label%22%3A%22w%22%2C%22folderId%22%3Anull%2C%22url%22%3A%22%23FF0000%22%2C%22comments%22%3A%22%22%2C%22position%22%3A%7B%22lat%22%3A39.426912683948%2C%22lng%22%3A-120.20892536635%7D%7D&tid=0V7V

在更好的语法中,POST请求如下所示:

URL=http://localhost:8080/rest/marker/
json: {"label":"my label here","folderId":null, "url":"#FF0000","comments":"","position":{"lat":39.2965796259061,"lng":-120.16708374023438}}
tid: "0V7V"

(请忽略数据值,它们在每个测试中都不同)

我尝试了以下几种变体:

a=requests.post("http://localhost:8080/rest/marker",data="json=%7B%22label%22%3A%22stuff%22%2C%22folderId%22%3Anull%2C%22url%22%3A%22%2300FF00%22%2C%22comments%22%3A%22%22%2C%22position%22%3A%7B%22lat%22%3A39.418%2C%22lng%22%3A-120.2%7D%7D&tid=0V7V")

a=requests.post("http://localhost:8080/rest/marker",json={"label":"stuff","folderId":"null","url":"#FF0000","comments":"","position":{"lat":39.4112,"lng":-120.2},"tid":"0V7V"})

a=requests.post("http://localhost:8080/rest/marker/",json={"label":"stuff","folderId":"null","url":"#FF0000","comments":"","position":{"lat":39.4112,"lng":-120.2}},data={"tid":"0V7V"})

我在响应文本中得到的堆栈跟踪始终以此开头, 这可能只是表明我做错了:

java.lang.ClassCastException: net.sf.json.JSONNull cannot be cast to
net.sf.json.JSONObject

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

试试这个:

import json

payload = {
    "label": "my label here",
    "folderId": None,  # converted to null by json serializer
    "url": "#FF0000",
    "comments":"",
    "position": {
        "lat":39.2965796259061,
        "lng":-120.16708374023438,
    }
}

response = requests.post(
    "http://localhost:8080/rest/marker",
    data={'json': json.dumps(payload), 'tid': '0V7V'}
)

根据您的问题中的详细信息,听起来服务器希望您发布一个包含名为json的字段的表单,其中包含json序列化字符串作为其值。

当您发送表单数据时,值必须为urlencoded ...但requests会自动为您执行此操作。您只需传入表单数据的字典,但仍需要将 json序列化有效负载作为json键的值。

您的第一个示例的问题是您已经对您的有效负载进行了urlencoded,因此当您将其传递给requests时,它将最终被双重编码。

在第二个示例中,您告诉requests发送json序列化的有效负载,就像原始POST主体而不是表单数据一样。