Java 尝试在Android中通过套接字发送utf-8格式的xml
我有一个Android应用程序,可以将xml文件发送到服务器。如果我将xml头的编码设置为utf-8,它将一直工作,直到出现一个奇怪的字符,例如日本符号,在这种情况下,服务器会拒绝xml,因为它不是utf-8。我无法控制服务器的工作方式,但它是一个已建立的产品,因此它不是他们的最终产品 在发送xml之前,我将包含它的字符串打印到终端,所有字符都正确显示 我如何知道我创建的字符串是否真的是utf-8,如果是,我如何通过套接字将其作为utf-8发送 以下是我将文件读入字符串的方式:Java 尝试在Android中通过套接字发送utf-8格式的xml,java,android,xml,sockets,utf-8,Java,Android,Xml,Sockets,Utf 8,我有一个Android应用程序,可以将xml文件发送到服务器。如果我将xml头的编码设置为utf-8,它将一直工作,直到出现一个奇怪的字符,例如日本符号,在这种情况下,服务器会拒绝xml,因为它不是utf-8。我无法控制服务器的工作方式,但它是一个已建立的产品,因此它不是他们的最终产品 在发送xml之前,我将包含它的字符串打印到终端,所有字符都正确显示 我如何知道我创建的字符串是否真的是utf-8,如果是,我如何通过套接字将其作为utf-8发送 以下是我将文件读入字符串的方式: file = n
file = new File (filePath);
FileReader fr = new FileReader (file);
BufferedReader br = new BufferedReader(fr);
// Reading the file
String line;
while((line=br.readLine())!=null)
data += line + '\n';
br.close();
这就是我发送字符串的方式
Socket socketCliente = new Socket();
try {
socketCliente.connect(new InetSocketAddress(address, port), 2000);
} catch (UnknownHostException e) {
getError("Host doesn't exist");
return -1;
} catch (IOException e) {
getError("Could not connect: The host is down");
return -1;
}
DataOutputStream serverOutput = null;
try {
serverOutput = new DataOutputStream(socketCliente.getOutputStream());
} catch (IOException e1) {
getError("Could not get Data output stream");
}
try {
serverOutput.writeBytes(data);
} catch (IOException e) {
getError("Could not write on server");
}
如果我在发送前打印“数据”字符串,所有字符都会正确显示
我已经尝试了无数种不同的方法来读入字符串,并以不同的方式写入套接字,但它们要么没有任何区别,要么阻止xml被完全接受,即使是使用标准字符
已解决:
我没有将文件读取为字符串,而是将其读取为字节数组,然后发送。
file = new File(filePath);
int size = (int) file.length();
data = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(data, 0, data.length);
buf.close();
} catch (FileNotFoundException e) {
getError("File not found");
} catch (IOException e) {
getError("Could not read from file");
}
Java通常使用UTF-16进行编码。具体来说,要使用UTF-8,您应该使用(与a一起使用)和(与套接字一起使用),并使用允许您指定所需字符集(在本例中为UTF-8)的构造函数变体
如果您在应用程序中使用,可以使用几个实用程序来帮助您实现这一点,包括Files.newReader()和ByteStreams.copy() 我刚试过,但服务器似乎不喜欢PrintWriter