我需要使用带有阿拉伯文本的Sinch API发送短信。我的短信包含 - 英语,阿拉伯语和数字。
我尝试了什么
以下是我尝试的代码
String arabicFormattedMessage = "Some English Text \n\n"+"رجى الاتصال بالامتثال التجاري وحماية المستهلك (ككب) من دائرة التنمية الاقتصادية في 12345678 لمزيد من التفاصيل، إذا لم يتم الاتصال في غضون 5 أيام عمل.";
jsonObject.put("message", arabicFormattedMessage );
String messageBody = new String(jsonObject.toString().getBytes(),"UTF-16BE");
String contentTypeHeader = "application/json; charset=UTF-16BE";
headers.put("authorization", base64AuthHeader);
headers.put("content-type", contentTypeHeader);
headers.put("x-timestamp", timeStampHeader);
//headers.put("encoding", "UTF-16BE"); Tried with and without this, but still not working.
回复我已经回复
Sinch responseCode: 400
Sinch Response: message object is invalid. toNumber object is invalid.
如评论中所述,以下是仅限英语的工作示例:
JSONObject jsonObject = new JSONObject();
String formattedMessage = "some english message";
jsonObject.put("message", formattedMessage );
final String messageBody = jsonObject.toString();
final String base64AuthHeader = "basic" + " " + base64AppDetails;
String contentTypeHeader = "application/json; charset=UTF-8";
final String timeStampHeader = DateUtil.getFormattedTimeString(new Date());
headers.put("authorization", base64AuthHeader);
headers.put("content-type", contentTypeHeader);
headers.put("x-timestamp", timeStampHeader);
HTTP POST请求
HttpClient.sendHttpPostRequest(url, messageBody, headers);
成功通话后,我收到来自Sinch的回复ID
答案 0 :(得分:1)
问题在于,无论你的字符串内部编码是什么(在Java中总是UTF-16),HttpClient.sendHttpPostRequest可能会将其作为UTF-8发送。
由于DefaultHttpClient已弃用,我们将使用HttpURLConnection以正确的方式执行此操作。您可能希望查看有关如何使用身份验证的HttpURLConnection Documentation。
String arabicFormattedMessage = "Some English Text \n\n"+"رجى الاتصال بالامتثال التجاري وحماية المستهلك (ككب) من دائرة التنمية الاقتصادية في 12345678 لمزيد من التفاصيل، إذا لم يتم الاتصال في غضون 5 أيام عمل.";
jsonObject.put("message", arabicFormattedMessage );
URL url = new URL ("http://...");
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
try {
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setRequestProperty("Content-Type","application/json; charset=UTF-16");
urlConn.connect();
DataOutputStream out = new DataOutputStream(urlConn.getOutputStream ());
out.writeBytes(URLEncoder.encode(jsonObject.toString(),"UTF-16"));
out.flush ();
out.close ();
int responseCode = urlConnection.getResponseCode();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
}
如果它不起作用,您还应该尝试UTF-16BE,或UTF-16LE,不带字节顺序标记。