【问题标题】:HTTP Error 400: Bad RequestHTTP 错误 400:错误请求
【发布时间】:2015-08-07 04:56:08
【问题描述】:

我正在使用 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

【问题讨论】:

  • 这不是 python 问题。您发送到该网址的网址和/或数据不正确。 http error 400 - 来自您尝试与之交谈的服务器。
  • 您正试图从localhost:8000 请求某些内容,但您没有说明该服务器正在运行什么。我们应该怎么知道?
  • @Two-BitAlchemist 是对的,您需要使用 xmlrpc 套接字或其他方式设置服务器

标签: python


【解决方案1】:

您似乎正在尝试将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 发布请求中设置正确的内容类型标头。 否则,默认内容类型将是application/x-www-form-urlencoded,就好像数据来自表单一样。

【讨论】: