我需要将一个阿拉伯值字符串作为参数传递给 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/