简体   繁体   中英

HTTP Error 400: Bad Request

I am learning python API testing using urllib2 module.I tried to execute the code.but throwing the following msg.Can anybody help me.Thanks in advance.

code:

url = "http://localhost:8000/HPFlights_REST/FlightOrders/"

data = {"Class" : "Business","CustomerName" :"Bhavani","DepartureDate" : "2015-10-12","FlightNumber" : "1304","NumberOfTickets": "3"}    
encoded_data = urllib.urlencode(data)
'''print encoded_data
print urllib2.urlopen(url, encoded_data).read()'''    
request = urllib2.Request(url, encoded_data)

print request.get_method()
request.add_data(encoded_data)
response = urllib2.urlopen(request)

Error:

Traceback (most recent call last):
  File "C:/Users/kanakadurga/PycharmProjects/untitled/API.py", line 44, in <module>
    createFlightOrder()
  File "C:/Users/kanakadurga/PycharmProjects/untitled/API.py", line 39, in createFlightOrder
    response = urllib2.urlopen(request)
  File "C:\Python27\lib\urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 437, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 550, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 475, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 409, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 558, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 400: Bad Request

Process finished with exit code 1

It looks like you are trying to post data to the server.

From the URL, I can make a wild guess and assume the server accepts the data in json format, probably.

If that is the case then you can do

import json

url = "http://localhost:8000/HPFlights_REST/FlightOrders/"
data = {"Class": "Business", "CustomerName": "Bhavani", "DepartureDate": "2015-10-12", "FlightNumber": "1304", "NumberOfTickets": "3"}    
encoded_data = json.dumps(data)

request = urllib2.Request(url, encoded_data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req) # issue the request
response = f.read() # read the response
f.close()
... # your next operations follow

The point is that you need to encode the data correctly (json) and also set the proper content-type header in the HTTP post request, which the server probably checks. Otherwise, the default content-type would be application/x-www-form-urlencoded , as if the data came from a form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM