HTTP错误400:错误请求

时间:2015-08-06 20:10:34

标签: python

我正在使用urllib2模块学习python API测试。我试图执行代码。但是抛出以下信息。任何人都可以帮助我。提前谢谢。

代码:

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)

错误:

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

1 个答案:

答案 0 :(得分:0)

您似乎正在尝试将data发布到服务器。

从URL中,我可以猜测并假设服务器可能接受json格式的数据。

如果是这种情况,那么你可以做

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

重点是您需要正确编码数据(json)并在HTTP post请求中设置正确的content-type标头,服务器可能会检查该标头。 否则,默认内容类型将为application/x-www-form-urlencoded,就好像数据来自表单一样。