对ASP站点的POST请求没有带来好结果

时间:2014-09-08 11:41:07

标签: python json python-2.7 xmlhttprequest python-requests

我尝试为ASP站点创建POST请求(就像在Firefox中一样),以获取JSON响应 但在我的代码中,响应是html,而不是JSON。

link to site

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 个答案:

答案 0 :(得分: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