简体   繁体   中英

how can convert String to UTF-8 without error catch

I need convert String to UTF-8. Now in my code I have this:

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

but encode method throw exception UnsupportedEncodingException

I rewrite: sb.append(smsAnswerText) becouse write this

and I have wrong tуxt -unreadable characters

Then I tried new String(smsAnswerText.getBytes(),StandardCharsets.UTF_8) And this method throw exception too UnsupportedEncodingException

How can I convert Sting to String+UTF-8 without UnsupportedEncodingException ?

I need:

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

I have

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

I don't think any provider is swallowing the exception.The alternative you can try is using

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

Here @SneakyThrows annotation is available.By Using this You can avoid throws and throw keywords

Why will not you do try cache block?

     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;

    }

or do some class like wrapper around this function:

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

}

and then:

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

But both sutiations are not good becouse this exception is need to understand how it can be handled when Encoding is wrong. You must exactly understand what you must do when this situation is come, because exception is supressed.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM