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

前端 未结 3 1342
独厮守ぢ
独厮守ぢ 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 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)
    

提交回复
热议问题