urllib2.HTTPError: HTTP Error 400: Bad Request - Python

前端 未结 3 1331
独厮守ぢ
独厮守ぢ 2021-01-28 18:34

I\'m trying to POST using urllib and urllib2 but it keeps giving me this error

    Traceback (most recent call last):
  File \"/Users/BaDRaN/Desktop/untitled tex         


        
相关标签:
3条回答
  • 2021-01-28 18:50

    My psychic powers suggest you want to send body as a string of json, not as a dictionary that's converted to a string.

    body = '{"where" : {"deviceType" : "ios"}, "data" : {"alert" : "vvv"}}'
    

    Notice the use of double-quotes for the json elements.

    0 讨论(0)
  • 2021-01-28 18:58

    I suspect your payload is not correctly encoded. Nowhere they say "urlencoded". Try using their own example instead. https://parse.com/docs/rest#push urrlib2 is a rather primitive library - using e.g. requests would be more convenient.

    0 讨论(0)
  • 2021-01-28 19:02

    It depends whether the json data is in correct format or not, or the issue is in the header content. Hence the urllib2.HTTPError: HTTP Error 400: Bad Request usually occurs.

    A small piece of code below with the basic64 authentication with the headers and the json data for the PUT/POST methods:

    import urllib2
    import base64
    import json
    url = 'Your_URL'
    auth = 'Basic ' + base64.encodestring('%s:%s' % ('username','password'))[:-1]
    content_header = {'Authorization': auth,
                     'Content-Type':'application/json',
                     'Accept':'application/json'}
    json_data = YOUR_DATA
    request = urllib2.Request(url=url, data=json.dumps(json_data), headers=content_header)
    request.get_method = lambda: 'PUT' #If you will not provide this, then it will be POST
    response = urllib2.urlopen(request)
    
    0 讨论(0)
提交回复
热议问题