How to handle Arabic in java

后端 未结 2 496
无人及你
无人及你 2021-01-26 12:15

i need to pass a string of arabic value to the HttpURL as a parameter but before i do say when i print the message its showing only question marks

public void s         


        
相关标签:
2条回答
  • 2021-01-26 12:55

    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();
    
    0 讨论(0)
  • 2021-01-26 13:10

    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));
    
    0 讨论(0)
提交回复
热议问题