Manas Chaturvedi
Manas Chaturvedi

Reputation: 5540

Google App Engine: HTTP Error 400: Bad Request

I'm working on an application which requires calculating the distance between two locations that were given as input by the user. I'm using Google Map's Distance Matrix API for this purpose. Here's the code:

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 contains a basic HTML form with input for the source and destination addresses. However, when I run this application, I get a HTTP Error 400: Bad Request. What's happening?

Upvotes: 2

Views: 2169

Answers (1)

Drewness
Drewness

Reputation: 5072

Your variables need to be urlencoded for the API request.

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

You can read more about .quote_plus here.

Upvotes: 3

Related Questions