urllib2.HTTPError: HTTP Error 400: Bad Request

刘超 12天前 ⋅ 102 阅读   编辑

一、描述

  使用模拟带header的请求,如下

import json
import ssl
from urllib2 import *
import urllib
import requests
from Cookie import SimpleCookie

url = "https://......"
params = {"start":"2020-09-01","end": "2020-09-03","metrics": [......],"dimensions": ["date"],"platform":"","app_bundle_id":"", "limit": 1000}
headers = {"x-userid":"***","x-authorization":"***","Content-Type":"application/json"}

params = urllib.urlencode(params).encode(encoding='utf-8')
req = Request(url=url, data=params, headers=headers)
print req
res = urlopen(req)

  报urllib2.HTTPError: HTTP Error 400: Bad Request错误

二、解决方法

  使用requests.post方法,如下

import json
import ssl
from urllib2 import *
import urllib
import requests
from Cookie import SimpleCookie

url = "https://......"
params = {"start":"2020-09-01","end": "2020-09-03","metrics": [......],"dimensions": ["date"],"platform":"","app_bundle_id":"", "limit": 1000}
headers = {"x-userid":"***","x-authorization":"***","Content-Type":"application/json"}

req = requests.post(url=url, data=json.dumps(params), headers=headers)

print req

注意:本文归作者所有,未经作者允许,不得转载

全部评论: 0

    我有话说: