向ASP网站发送POST请求时结果不佳
我想向一个ASP网站发送POST请求(就像在Firefox中那样),目的是获取JSON格式的响应。
但是在我的代码中,返回的是HTML,而不是JSON。
Firebug的响应头:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 08 Sep 2014 11:32:22 GMT
Content-Length: 101
Firebug的请求头:
POST /Portal/WebPageMethods/Playlista/playlist.aspx HTTP/1.1
Host: www.polskieradio.pl
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: pl,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://www.polskieradio.pl/10,Czworka.json
Content-Length: 17
Cookie: cookies-accepted=true; ASP.NET_SessionId=35p3kig5t5cmlikubnlnytlh
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
源代码:
import requests
import json
url = "http://www.polskieradio.pl/Portal/WebPageMethods/Playlista/playlist.aspx?program=4&count=1"
payload = { "Host": "www.polskieradio.pl",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0",
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Language": "pl,en-US;q=0.7,en;q=0.3",
"Accept-Encoding": "gzip, deflate",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"X-Requested-With": "XMLHttpRequest",
"Referer": "http://www.polskieradio.pl/10,Czworka",
"Content-Length": "17",
"Cookie": "cookies-accepted=true; ASP.NET_SessionId=5l1eezrjfdyvvevxushojtc2",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Cache-Control": "no-cache"
}
r = requests.post(url, data=json.dumps(payload))
print(r.headers['content-type'])
print r.content
我该怎么做才能正确实现呢?
谢谢大家的回答!
1 个回答
2
试试稍微不同的方法...
看看这个例子:
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)
Accept
是一个头部,不是负载。
你发送的所有负载,实际上都是头部信息。你的 POST 负载可以是 program=4&count=1
,或者你也可以使用 GET 方法。
--- 这里补充一下最终的解决方案
import requests
import json
url = "http://www.polskieradio.pl/Portal/WebPageMethods/Playlista/playlist.aspx"
data = 'program=4&count=1'
headers = {
'User-Agent': 'curl/7.35.0',
'Host': 'www.polskieradio.pl',
'Accept':'*/*',
'Proxy-Connection': 'Keep-Alive',
'Content-Type': 'application/x-www-form-urlencoded'
}
r = requests.post(url, data=data, headers=headers)
print r.content