0

When I send the following URL using my application I am running into following error:

Server returned HTTP response code: 400 for URL: http://maps.googleapis.com/maps/api/distancematrix/xml?origins=Medical Centre+ 308 George Street+ Sydney&destinations= Science Museum Exhibition Road London SW7 2DD&mode=driving&sensor=false

But by entering the URL into your browser would find out that its correct!!

Eme Emertana
  • 561
  • 8
  • 14
  • 29

2 Answers2

1

You probably need to urlencode the url before you fetch the it. Take a look at Java URL encoding of query string parameters

Community
  • 1
  • 1
Nathan Villaescusa
  • 17,331
  • 4
  • 53
  • 56
1

You may please encode the request URL before you open the connection to read the data. Please have a look at the below code for better understanding:

package com.stackoverflow.works;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;

public class URLReader {
    /*
     * @author: sarath_sivan
     */

    public static void read(String url) throws IOException {
        setProxy();//only invoke this method if you are using any proxy to open connection
        URL httpURL = new URL(url);
        BufferedReader bufferedReader = new BufferedReader(
        new InputStreamReader(httpURL.openStream()));

        String inputLine;
        while ((inputLine = bufferedReader.readLine()) != null) {
            System.out.println(inputLine);
        }   
        bufferedReader.close();
    }

    public static void setProxy() {
        System.getProperties().put("http.proxyHost", "xxx.xxx.xx.xx");//replace with your proxy
        System.getProperties().put("http.proxyPort", "8080");
    }

    public static String encodeURL(String url) throws UnsupportedEncodingException {//encoding your request url parameters here
        StringBuilder encodedURL = new StringBuilder(url);
        encodedURL.append("?origins=").append(encode("Medical Centre+ 308 George Street+ Sydney"));
        encodedURL.append("&destinations=").append(encode(" Science Museum Exhibition Road London SW7 2DD"));
        encodedURL.append("&mode=").append("driving");
        encodedURL.append("&sensor=").append("false");
        return encodedURL.toString();
    }

    public static String encode(String string) throws UnsupportedEncodingException {
        return URLEncoder.encode(string, "ISO-8859-1");
    }

    public static void main(String[] args) throws IOException {
        String url = "http://maps.googleapis.com/maps/api/distancematrix/xml";
        read(encodeURL(url));
    }

}

The output looks like this: enter image description here

1218985
  • 7,531
  • 2
  • 25
  • 31