Google App Engine:HTTP错误400:错误请求

时间:2014-03-11 22:29:57

标签: python google-maps google-app-engine google-maps-api-3

我正在处理一个应用程序,该应用程序需要计算用户输入的两个位置之间的距离。我为此目的使用Google Map的Distance Matrix API。这是代码:

class MainPage(Handler):
    def get(self):
        self.render('map.html')
    def post(self):
        addr1 = self.request.get("addr1")
        addr2 = self.request.get("addr2")
        url = 'http://maps.googleapis.com/maps/api/distancematrix/json?origins=' + addr1 + '&destinations=' + addr2 + '&mode=driving&sensor=false'
        link = urllib2.urlopen(url).read()
        self.response.write(link)

map.html

<html>
<head>
<title>Fare Calculator</title>
</head>
<body>
    <form method = "post">
        Source<input type = 'text' name = "addr1">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        Destination<input type = 'text' name = "addr2">
        <br><br>
        <input type = "submit" value = "Calculate Fare">
    </form>
</body>
</html>

map.html包含一个基本的HTML表单,其中包含源和目标地址的输入。但是,当我运行此应用程序时,我收到HTTP错误400:错误请求。发生了什么?

1 个答案:

答案 0 :(得分:3)

您的变量需要针对API请求进行urlencoded。

...    
url = 'http://maps.googleapis.com/maps/api/distancematrix/json?origins=' + urllib.quote_plus(addr1) + '&destinations=' + urllib.quote_plus(addr2) + '&mode=driving&sensor=false'
...

您可以详细了解.quote_plus here