SORU
3 Mart 2009, Salı


Benzer bir çıktı üretir Java JavaScript eşdeğer'In encodeurıcomponent?

Ben deneme ile çeşitli bit Java kod çalışıyor ama bir şey olacak kodlamak bir dize içeren tırnak, boşluk ve "egzotik" Unicode karakterleri ve üretmek çıktı bu aynı JavaScript encodeURIComponent işlevi.

Benim test dize işkence:""B". ±

Firebug aşağıdaki JavaScript elimde şöyle bir ifade girin:

encodeURIComponent('"A" B ± "');

ve Sonra ben -:

""A" B ± ""

İşte küçük bir test Java programım:

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class EncodingTest
{
  public static void main(String[] args) throws UnsupportedEncodingException
  {
    String s = "\"A\" B ± \"";
    System.out.println("URLEncoder.encode returns "
        URLEncoder.encode(s, "UTF-8"));

    System.out.println("getBytes returns "
        new String(s.getBytes("UTF-8"), "ISO-8859-1"));
  }
}

&; Bu program çıktıları -:

URLEncoder.encode returns "A" B ± "
getBytes returns "A" B ± "

Hayır, ama yakın! UTF-8 dize JavaScript encodeURIComponent aynı çıktıyı üretir, böylece Java ile kodlama en iyi yolu nedir?

DÜZENLEME:Kısa bir süre Java 1.4 Java 5 için hareketli kullanıyorum.

CEVAP
4 Mart 2009, ÇARŞAMBA


Bu kadar sonunda buldum sınıfı

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * Utility class for JavaScript compatible UTF-8 encoding and decoding.
 * 
 * @see http://stackoverflow.com/questions/607176/java-equivalent-to-javascripts-encodeuricomponent-that-produces-identical-output
 * @author John Topley 
 */
public class EncodingUtil
{
  /**
   * Decodes the passed UTF-8 String using an algorithm that's compatible with
   * JavaScript's <code>decodeURIComponent</code> function. Returns
   * <code>null</code> if the String is <code>null</code>.
   *
   * @param s The UTF-8 encoded String to be decoded
   * @return the decoded String
   */
  public static String decodeURIComponent(String s)
  {
    if (s == null)
    {
      return null;
    }

    String result = null;

    try
    {
      result = URLDecoder.decode(s, "UTF-8");
    }

    // This exception should never occur.
    catch (UnsupportedEncodingException e)
    {
      result = s;  
    }

    return result;
  }

  /**
   * Encodes the passed String as UTF-8 using an algorithm that's compatible
   * with JavaScript's <code>encodeURIComponent</code> function. Returns
   * <code>null</code> if the String is <code>null</code>.
   * 
   * @param s The String to be encoded
   * @return the encoded String
   */
  public static String encodeURIComponent(String s)
  {
    String result = null;

    try
    {
      result = URLEncoder.encode(s, "UTF-8")
                         .replaceAll("\\ ", " ")
                         .replaceAll("\\!", "!")
                         .replaceAll("\\'", "'")
                         .replaceAll("\\(", "(")
                         .replaceAll("\\)", ")")
                         .replaceAll("\\~", "~");
    }

    // This exception should never occur.
    catch (UnsupportedEncodingException e)
    {
      result = s;
    }

    return result;
  }  

  /**
   * Private constructor to prevent this class from being instantiated.
   */
  private EncodingUtil()
  {
    super();
  }
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Harvest: Greg Laurie

    Harvest: Gre

    6 HAZİRAN 2006
  • NLthomas21

    NLthomas21

    20 Mayıs 2008
  • Pepsi

    Pepsi

    1 Kasım 2005