1

In order to make a good String formated url from a previous String I want to know how to encode a String in an other but encoded in UTF-8 ?

My method to encode is here :

public static String getUrlScheme(Context ctx, String title,
            String description, double latitude, double longitude) {

        try {

            String titleUtf8 = URLEncoder.encode(title, "utf-8");
            String descriptionUtf8 = URLEncoder.encode(description, "utf-8");

            String urlScheme = ctx.getResources().getString(
                    R.string.url_scheme_base)
                    + "?title="
                    + titleUtf8
                    + "&descr="
                    + descriptionUtf8
                    + "&lat=" + latitude + "&long=" + longitude;

            return urlScheme;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

For example I got :

title : "T çé ü" desc : "" ==>

http://..?title=T+%C3%A7%C3%A9+%C3%BC&descr=&lat=...&long=..

And the correct url should be (from iOS method) ==> http://..?title=T%20%C3%A7%C3%A9%20%C3%BC&descr=%20&lat=...&long=...

title : "HB s6/&" desc : "" ==> http://..?title=HB+s6&descr=&lat=..long=..

And the correct url should be (from iOS method) ==> http://..?title=HB%20s6&descr=%20&lat=...&long=...

The problem is that in iOS, using this method : stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding my friend can have a good String encoded in UTF-8.

Please help

EDIT

Solved by replacing "+" by "%20" :

String titleUtf8 = URLEncoder.encode(title, "utf-8").replaceAll("\\+", "%20");
String descriptionUtf8 = URLEncoder.encode(description, "utf-8").replaceAll("\\+", "%20");
eento
  • 761
  • 4
  • 20
  • 53
  • iOS uses %20 escape for an empty space character and Android URLEncode uses + espcape. Both are valid url escaping for an empty character. Use encodedStr.replaceAll("+", "%20") to make them identical. – Whome Oct 09 '13 at 16:58
  • Thanks, I solved just replacing all "+" by "%20" – eento Oct 09 '13 at 17:06
  • encodedStr.replaceAll("\\+", "%20") is better. "+" should be escaped. – toto_tata Nov 22 '16 at 14:30

1 Answers1

-1

In Android you also have very fine tools : URL encoding in Android

String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "https://stackoverflow.com/search?q=" + query;
Community
  • 1
  • 1
TN888
  • 7,659
  • 9
  • 48
  • 84