How to handle Arabic in java

北慕城南 提交于 2019-12-02 08:25:28

Assuming that SendSms.getMessage() returns a String, what did you intend with this line?

String message = new String(object.getMessage().getBytes(), "UTF-8");

Encoding and decoding the message is a waste at best—if it works, you will just get back the string you started with. And it will only work if the default encoding is UTF-8. In this case, it's corrupting the message.

When you encode a String with getBytes(), the platform default encoding is used. Unless the system's native character set supports Arabic, any Arabic character will be replaced with a supported character, usually ?.

Try this instead:

String message = object.getMessage();

At the very least, you need to follow the advice in erickson’s answer. If there is still a problem, read on…

A Windows command window is pretty limited in what characters it can display. I don’t know how various language packs and code pages affect it, but I know an English edition of Windows will display Arabic characters (and most characters above U+00FF) as ?.

So it’s entirely possible that your characters are correct, they are just being shown as ? when printed.

Instead of using System.out.println, use a Logger. Then you can add a Handler to your Logger (or the root Logger) which writes to a file, and you can examine that file:

private static final Logger logger =
    Logger.getLogger(SmsSender.class.getName());

// ...

public void sendSms(SendSms object) throws IOException {

    String message = new String(object.getMessage().getBytes(),
        StandardCharsets.UTF_8);
    logger.info(() -> "Message=\"" + message + "\"");

    // ...

    int responseCode = con.getResponseCode();
    logger.info(() -> "Sending 'POST' request to URL : " + url);
    logger.info(() -> "Post parameters : " + urlParameters);
    logger.info(() -> "Response Code : " + responseCode);

(By the way, MalformedURLException and ProtocolException are both subclasses of IOException, so you only need throws IOException in your method signature. It inherently covers the other two exceptions.)

In some other class, presumably in your main method:

int logFileMaxSize = 10 * 1024 * 1024;  // 10 MB
Logger.getLogger("").addHandler(
    new FileHandler("%h/Sms-%g.log", logFileMaxSize, 10));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!