taslan
taslan

Reputation: 33

URL string on HttpURLConnection

Consider following code for an android app;

private String GetDistance(String src, String dest) {     
    StringBuilder urlString = new StringBuilder();
    urlString.append("http://maps.googleapis.com/maps/api/distancematrix/json?");
    urlString.append("origins=");   // **"ÇANKIRI,ÇERKEŞ,TURKEY"**
    urlString.append(src);
    urlString.append("&destinations="); // **"ANKARA,ALTINDAĞ,TURKEY"**
    urlString.append(dest);
    urlString.append("&mode=driving&sensor=false");

    Log.d("xxx","URL="+urlString.toString());

    // get the JSON And parse it to get the directions data.
   HttpURLConnection urlConnection= null;
   URL url = null;

   //String urlStr = URLEncoder.encode(urlString.toString(), "utf-8");
   //url = new URL(urlStr);
   url = new URL(urlString.toString());
   ......

if src and dest strings have unicode characters, google distance matrix service fails (status returns as NOT_FOUND). But if I use the strings in google map site within a web browser, it returns good result. I tried to use also URLEncoder, but I it fails as well.

Do you have any suggestion ?

Upvotes: 3

Views: 637

Answers (1)

Okan Kocyigit
Okan Kocyigit

Reputation: 13441

you should use URLEncoder.encode,

example

urlString.append(URLEncoder.encode(dest, "utf-8"));

edit: don't forget you should use it just for paramaters, not whole url.

Upvotes: 3

Related Questions