2015-06-20 77 views
0

我正在構建一個Android應用程序,並且存在應用程序的一部分,我需要使用某些表單數據發佈到某個網址。我傳遞的一個表單域是一個電子郵件地址。在Java中轉義保留的url參數

我注意到一些問題,其中一些電子郵件地址有一個'+'號,它們是URL中的一個保留字符,意思是''。我想知道,在我將其轉換爲後綴byte []之前,我如何在代碼中清理/轉義像這樣和其他字符。我不想做一個replaceAll。有沒有一種內置於Java的特定編碼器可以做到這一點?

這裏是我使用的代碼:

StringBuilder builder = new StringBuilder(); 
builder.append(ID + "=" + params.id + "&"); 
builder.append(LOCALE + "=" + params.locale + "&"); 
builder.append(EMAIL + "=" + params.getEmail()); 

String encodedParams = builder.toString(); 
mWebView.postUrl(URL, EncodingUtils.getAsciiBytes(encodedParams)); 
+0

這不是直接回答你的問題,而是一個+通常意味着忽略+及其之後的所有的電子郵件的用戶名部分。例如,[email protected]轉到[email protected],但當您想要輕鬆過濾發送到您地址的郵件時,可用於註冊網站。 – mikeb

回答

0

替換%2B加號。你必須對它進行編碼才能在url中使用它,否則它將被視爲空間。那麼在你的服務器端你可以通過html解碼電子郵件。

+0

如何在不明確更換字符串的情況下執行此操作。應該有一些方法來做到這一點內置到Java框架沒有? –

+0

builder.append(EMAIL +「=」+ TextUtils.htmlEncode(params.getEmail())); – Helmi

2

嘗試使用java.net.URLEncoder.encode(valueToEncode,「UTF-8」);

我已經看了細節已經有一段時間了,但是我認爲在連接它們之前,必須在字符串的各個部分調用encode()。

的工具方法如下一直工作很適合我:

/** 
    * Given a {@link Map} of keys and values, this method will return a string 
    * that represents the key-value pairs in 
    * 'application/x-www-form-urlencoded' MIME format. 
    * 
    * @param keysAndValues 
    *   the keys and values 
    * @return the data in 'application/x-www-form-urlencoded' MIME format 
    */ 
    private String wwwFormUrlEncode(Map<String, String> keysAndValues) { 
     try { 
      StringBuilder sb = new StringBuilder(); 
      boolean isFirstEntry = true; 
      for (Map.Entry<String, String> argument : keysAndValues.entrySet()) { 
       if (isFirstEntry) { 
        isFirstEntry = false; 
       } else { 
        sb.append("&"); 
       } 
       sb.append(URLEncoder.encode(argument.getKey(), "UTF-8")); 
       sb.append("="); 
       sb.append(URLEncoder.encode(argument.getValue(), "UTF-8")); 
      } 
      return sb.toString(); 
     } catch (UnsupportedEncodingException e) { 
      //it is unlikely that the system does not support UTF-8 encoding, 
      //so we will not bother polluting the method's interface with a checked exception 
      throw new RuntimeException(e); 
     } 
    }