Python 无法使用 urllib2 进行 PUT

标签 python json urllib2

我正在尝试使用 urllib2 进行 http 放置。

服务器管理员说我需要提供以下格式的数据: {“类型”:“存储”,“数据”:[“9953”]}

我的代码如下:

url = 'https://url.com/polling/v1/5cb401c5-bded-40f8-84bb-6566cdeb3dbb/stores'
request = urllib2.Request(url, data='{\"type\":\"store\",\"data\":[\"9953\"]}')
request.add_header("Authorization", "Basic %s" % creds)
request.add_header("Content-type", "application/json")
request.add_header("Accept", "application/json")
print "Data: %s" % request.get_data()
print "Accept: %s" % request.get_header("Accept")
print "Content-Type: %s" % request.get_header("Content-type")
print "Authorization: %s" % request.get_header("Authorization")
try:
    result = urllib2.urlopen(request, data )
except urllib2.HTTPError as e:
    print e.read()
    exit()
data = json.loads(result.read())
print data

我运行时的输出是:

Data: {"type":"store","data":["9953"]}
Accept: application/json
Content-Type: application/json
Authorization: Basic U1lTQ1RMOmFiYzEyMw==

这正是我被告知要发送的内容

但我收到以下错误:

BWEB000065: HTTP Status 400 - org.codehaus.jackson.JsonParseException: Unexpected end-of-input: expected close marker for ARRAY (from [Source: org.jboss.resteasy.core.interception.MessageBodyReaderContextImpl$InputStreamWrapper@695dd38d; line: 2, column: 15])

如有任何帮助,我们将不胜感激。

最佳答案

注意这两行代码:

request = urllib2.Request(url, data='{\"type\":\"store\",\"data\":[\"9953\"]}')

result = urllib2.urlopen(request, data)

在第一行中,您通过将 data 命名参数集传递给 JSON 负载来初始化请求。这似乎是正确的。

然而,第二行传入了data,覆盖了你在第一行初始化的payload。我假设这里的 data 是程序更大上下文中的某个变量(原始问题中未显示),并且此 data 变量设置为某个不同的值,可能是无效的 JSON 负载。

如果第一行的payload初始化正确,那么我建议把第二行改成这样:

result = urllib2.urlopen(request)

关于Python 无法使用 urllib2 进行 PUT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45106749/

相关文章:

python - Python 装饰器可以用来返回非函数对象吗?

python - Python 错误的 Quantlib-SWIG 1.12.x,在 Windows 中缺少 Quantlib/quantlib_wrap.cpp

javascript - ASP.NET MVC : Timer not working in IE

python - 如何使用 Python 抓取具有动态生成的 URL 的页面?

python - 如何使urlib在python中返回数组-解析对elasticsearch的调用结果?

python - 如何在matplotlib中添加箱线图来散布数据

php - Python 相当于 PHP Mcrypt

c# - Newtonsoft.Json.Linq.JArray' 键入 'System.Collections.Generic.IEnumerable

android - 重复输入错误 - 带有 GSON 的 JSONPath

python - 向 Dynamics CRM Web API 发出请求