我正在开发我的 android 项目。我必须通过我的 android 应用程序向服务器应用程序发送一些单词。发送后,我将能够搜索一些调查并将其返回给客户。我的用户使用“波斯语”字符来搜索合适的主题。
我发现当我将它们(波斯语单词فارسی
)发送到服务器时,它无法正确识别它们。它适用于“????”而不是正确的单词流。它只是从 Android 应用程序而不是英语单词发送的波斯语单词有这个问题。我从未尝试过其他语言,但我认为它们也有这个问题。我认为移动设备对波斯语字符有不同的代码,而放置在服务器中的 C# 代码无法翻译波斯语单词。让我告诉你,我使用 C# 实现服务器端,使用 Java 实现 Android 应用程序,数据库是 SQL Server 2010。
我使用查询字符串来捕获参数。之后,我使用此参数进行查询,该查询从数据库返回主题。 C#:
string Tag = Request.QueryString["Tag"].ToString();
java :
这部分展示了我如何将参数发送到服务器。我认为这是通过 HTTP 协议(protocol)发送参数的常用方式。
HttpURLConnection urlConnection = null;
try{
URL myUrl=new URL("http://10.0.2.2:80/Urgence/SearchResault.aspx?Tag="+Tag);
urlConnection = (HttpURLConnection)myUrl.openConnection();
BufferedReader in = new BufferedReader (new InputStreamReader(urlConnection.getInputStream()));
String temp="";
// Data is used to store Server's Response
while((temp=in.readLine())!=null)
{
Data=Data+temp;
}
}
我该如何解决我的问题?
最佳答案
简答
use UTF-8 encoding
如果你有一个
String message = ...;
这被转换为字节[]
byte[] bytes = message.getBytes();
那么DatagramPacket必须使用
构造new DatagramPacket(bytes, bytes.length(), ... );
你的通话使用
new DatagramPacket( message.getBytes, message.length(),..,
但这使用字符串长度,但波斯语要求每个字符超过一个字节。
字符串فارسی
有5个字符,但是UTF-8编码需要10个字节。您需要发送 10 个字节。UTF-8 编码的字母表中的一个字母需要 2 个字节,因此这个具有 5 个字母的单词被编码为 10 个字节。数据报包长度必须以字节计数给出。
更新
将参数
设置为:
String parameters = "parameter1=" + URLEncoder.encode("YOUR_STRING_TO_ENCODE","UTF-8");
然后,在 AsyncTask 下:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(params.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(params);
out.close();
String response = "";
Scanner inStream = new Scanner(conn.getInputStream());
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
然后,你将从服务器得到结果:
-movaffagh baash
关于java - 在android中解码字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30055020/