2013-10-09 89 views
1

爲了從前一個字符串中創建一個好的String格式的URL我想知道如何在另一個字符串中編碼一個字符串,但以UTF-8編碼?UTF-8網址的字符串編碼

我對編碼方法是在這裏:

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(); 
     } 

比如我:

標題: 「T CEü」 說明: 「」 ==>

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

而正確的網址應該是(來自iOS方法)==>http://..?title=T%20%C3%A7%C3%A9%20%C3%BC&descr=%20&lat=...&long=...

title:「HB s6/&「說明: 」「 ==>http://..?title=HB+s6&descr=&lat=..long=..

和正確的網址應該是(來自iOS的方法)==>http://..?title=HB%20s6&descr=%20&lat=...&long=...

的問題是,在iOS上,使用這種方法:stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding我的朋友可以有一個用UTF-8編碼的好字符串。

請幫

編輯

替換 「+」 由 「%20」 解決:

String titleUtf8 = URLEncoder.encode(title, "utf-8").replaceAll("\\+", "%20"); 
String descriptionUtf8 = URLEncoder.encode(description, "utf-8").replaceAll("\\+", "%20"); 
+0

iOS使用%20轉義獲取空白字符和Android URLEncode使用+ espcape。兩者都是有效的url轉義爲空字符。使用encodedStr.replaceAll(「+」,「%20」)使它們相同。 – Whome

+0

謝謝,我解決了只是用「%20」取代所有「+」 – eento

+0

encodedStr.replaceAll(「\\ +」,「%20」)更好。 「+」應該逃脫。 –

回答

-1

在Android中你也有很細的工具:URL encoding in Android

String query = URLEncoder.encode("apples oranges", "utf-8"); 
String url = "https://stackoverflow.com/search?q=" + query; 
+0

你是在開玩笑嗎?!在發帖之前保留一下我的方法! – eento