java - 如何在java中处理阿拉伯语

标签 java httprequest httpurlconnection

我需要将一个阿拉伯值字符串作为参数传递给 HttpURL,但在我说打印消息时它只显示问号

public void sendSms(SendSms object) throws MalformedURLException,ProtocolException,IOException  {

    String message=new String(object.getMessage().getBytes(), "UTF-8");
    System.out.println(message);//printing only question marks
}

即使我将消息作为 url 参数发送,它也不会将原始消息作为阿拉伯语发送,而是发送问号。

public void sendSms(SendSms object) throws MalformedURLException, ProtocolException,IOException  {

    String message=new String(object.getMessage().getBytes(), "UTF-8");
    System.out.println(message);
    PrintStream out = new PrintStream(System.out, true, "UTF-8");
    out.print(message);
    String charset="UTF-8";


    URL url = new URL("http://62.215.226.164/fccsms_P.aspx");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestProperty("Accept-Charset", charset);

    con.setRequestMethod("POST");

    //con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en,ar_KW;q=0.5");
    con.setRequestProperty("Content-Type", "text/html;charset=utf-8");
    String urlParameters =       "UID=test&P=test&S=InfoText&G=965"+object.getPhone()+"&M= Hello "+object.getName()+" "+message+" &L=A";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

}

最佳答案

假设 SendSms.getMessage() 返回一个 String,您对这一行的意图是什么?

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

对消息进行编码和解码充其量只是一种浪费 - 如果有效,您将只返回开始时使用的字符串。仅当默认编码为 UTF-8 时它才有效。在这种情况下,它会破坏消息。

当您使用 getBytes()String 进行编码时,将使用平台默认编码。除非系统的 native 字符集支持阿拉伯语,否则任何阿拉伯字符都将被替换为支持的字符,通常是 ?

试试这个:

String message = object.getMessage();

关于java - 如何在java中处理阿拉伯语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39729307/

相关文章:

java - 您能否以编程方式连接到一系列网页并解析源 HTML,而不会对系统造成压力或引发危险信号?

CXF - 捕获/处理 HTTP 异常

java - 使用 "join"获取模式时如何停止 hibernate 返回多个实例?

android - 连接超时

java.net.HttpURLConnection 检查/测试连接,而只有 POST 方法可用

c# - 我是否必须关闭我的代码从未访问过的 HttpRequest 输入流?

go - golang 中的 http HandleFunc 参数

java - 将广泛的 C++ 库与具有非原始参数的 JNI 一起使用

java - 这个运算符 |= 是什么意思?

java - 文件系统和 Java 中的 jar/zip 上的抽象层