【问题标题】:how can convert String to UTF-8 without error catch如何将字符串转换为 UTF-8 而不会出现错误捕获
【发布时间】:2017-02-16 10:44:29
【问题描述】:

我需要将字符串转换为 UTF-8。现在在我的代码中我有这个:

sb.append(URLEncoder.encode(smsAnswerText, "UTF-8"))

但是encode方法抛出异常UnsupportedEncodingException

我重写:sb.append(smsAnswerText) 因为写this

我输入了错误的 tуxt -不可读字符

然后我尝试了new String(smsAnswerText.getBytes(),StandardCharsets.UTF_8) 而且这个方法也抛出异常UnsupportedEncodingException

如何在没有UnsupportedEncodingException 的情况下将 Sting 转换为 String+UTF-8?

我需要:

public static String generateBodyResponse(String smsAnswerText){
    return// smsAnswerText in UTF-8
}

我有

public static String generateBodyResponse(String smsAnswerText) throws UnsupportedEncodingException{
        return URLEncoder.encode(smsAnswerText, "UTF-8");
    }

【问题讨论】:

  • 你的意思是它在运行时抛出异常还是需要将它包装到 try...catch 中,因为已检查异常?
  • 我经常使用这个方法,不想抛出这个异常。也许有一种方法可以在不释放异常的情况下进行转换

标签: java string utf-8


【解决方案1】:

你为什么不尝试缓存块?

     public static String generateBodyResponse(String smsAnswerText) {
String defaultval= "some default value which will be returned if your encod is wrong.";
        try {
            defaultval = URLEncoder.encode(smsAnswerText, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return defaultval;

    }

或者围绕这个函数做一些类似包装的类:

public class URLEncoderDecorator {
public static String encode(String smsAnswerText) {
    try {
        return URLEncoder.encode(smsAnswerText, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return smsAnswerText;
}

}

然后:

public static String generateBodyResponse(String smsAnswerText) {
    return URLEncoderDecorator.encode(smsAnswerText, "UTF-8");
}

但这两种情况都不好,因为这个异常需要了解在编码错误时如何处理。当这种情况发生时,你必须准确地理解你必须做什么,因为异常被抑制了。

【讨论】:

  • e.printStackTrace();是不好的做法。是的,我可以将 ecxeption 捕获到我的方法中并添加到 Log this ecxeption。但如果我收到错误消息,我会以非 utf-8 格式返回消息。
  • e.printStackTrace() 不是一种做法。它是 ide 自动生成的模板。 :) 。或记录器或其他东西。当你得到错误的编码时,我不明白你的行为。你会怎么做?如果您知道可以将其放入 catch 块中或将默认值作为回报。否则,您必须抛出异常并在您的应用可以理解的其他地方处理它。
【解决方案2】:

我认为没有任何提供者正在吞下异常。您可以尝试的替代方法是使用

<dependency>                               
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>0.10.0</version>
<scope>compile</scope>
</dependency>

这里有@SneakyThrows注解,使用这个可以避免 throws 和 throw 关键字

【讨论】:

    【解决方案3】:
    import java.nio.charset.StandardCharsets;
    import org.apache.commons.codec.net.URLCodec;
    
    byte[] urlEscape(String s) {
        return new URLCodec().encode(s.getBytes(StandardCharsets.UTF_8));
    }
    

    【讨论】:

      猜你喜欢
      • 2013-03-02
      • 1970-01-01
      • 2013-08-20
      • 2010-09-21
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 2010-11-03
      相关资源
      最近更新 更多