Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python发布JSON并读取响应_Python_Json_Urllib2_Python Requests - Fatal编程技术网

使用python发布JSON并读取响应

使用python发布JSON并读取响应,python,json,urllib2,python-requests,Python,Json,Urllib2,Python Requests,我正在尝试用python发出post请求,我相信我做的一切都是正确的。但是,它没有返回任何响应。我似乎不知道我的要求是否有什么问题。如果我没有得到任何回复,服务可能有问题。我在这里写的东西有什么内在的错误吗 import json import urllib2 data = {'first_name': 'John','last_name': 'Smith','email': 'johnsmith@smith.com','phone': '215-555-1212'} req = urlli

我正在尝试用python发出post请求,我相信我做的一切都是正确的。但是,它没有返回任何响应。我似乎不知道我的要求是否有什么问题。如果我没有得到任何回复,服务可能有问题。我在这里写的东西有什么内在的错误吗

import json
import urllib2

data = {'first_name': 'John','last_name': 'Smith','email': 'johnsmith@smith.com','phone': '215-555-1212'}

req = urllib2.Request('https://someurl.io/')
req.add_header('Content-Type', 'application/json')

response = urllib2.urlopen(req, json.dumps(data))
print response.read()
print response.headers

老实说,除非您喜欢urllib2,否则我建议使用。以下是请求中的相同数据代码:

import requests
import json

payload = {'first_name': 'John','last_name': 'Smith','email': 'johnsmith@smith.com','phone': '215-555-1212'}
url = 'https://someurl.io/'

r = requests.post(url, json=json.dumps(payload))

print r.content
print r.headers

不是对你的问题的直接回答,但是使用
urllib2
是一种痛苦。尝试我想你会喜欢的。它通常是一个简单得多的API。消除了大量的锅炉板。甚至有一个很好的方法。