gpt4 book ai didi

c# - 为什么 DataInputStream.readline 在字符串开头添加奇怪的字节

转载 作者:行者123 更新时间:2023-12-01 19:03:54 25 4
gpt4 key购买 nike

从 C# 服务器发送 XML 并在 Android Java 客户端中接收它

这是收到的 XML 的样子:

<?xml version="1.0" encoding="utf-8"?>.....

这是c#发送代码

// convert the class WorkItem to xml
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(WorkItem));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, p);

// send the xml version of WorkItem to client
byte[] data = memoryStream.ToArray();
clientStream.Write(data, 0, data.Length);
Console.WriteLine(" send.." + data);
clientStream.Close();

在 Java 中我只是这样做:

in = new DataInputStream(skt.getInputStream());
String XMlString = in.readLine();

如果我每次从 XMlString 中删除前 3 个字符,一切都会正常。
如果可能的话,我真的很想以更好的方式做到这一点

*更新添加 Android java 客户端

@Override
protected String doInBackground(Long... params) {

textTopInfo.setText("Loading workitems..");

DataOutputStream out = null;
DataInputStream in = null;

try {

Socket skt = new Socket(Consts.SERVER_URL_1, Consts.SERVER_PORT_1);
skt.setSoTimeout(10000); //10 sec timout
out = new DataOutputStream(skt.getOutputStream());
in = new DataInputStream(skt.getInputStream());

// check valid user id
String id = prefs.getString("id", "");

if(id.equals(""))
return "Open menu and enter User Id";

String theString = Consts.PUSH_GET_WORKITEM + ":" + id ;

out.write(theString.getBytes());

BufferedReader d = new BufferedReader
(new InputStreamReader(skt.getInputStream()));
String XMlString = d.readLine();

// here I remove the BOM
XMlString = XMlString.substring(3);

Log.d(TAG, "GF");

XStream xstream = new XStream();
xstream.alias("WorkItem", WorkItem.class);
xstream.alias("OneItem", OneItem.class);
pl = (WorkItem)xstream.fromXML(XMlString);

} catch (Exception e) {

return "cannot connect to server " + e.toString();

}finally{
//kill out/in
try {
if(out != null)
out.close();
if(in!=null)
in.close();
} catch (IOException e) {

}
}
return "here is the list";
}

最佳答案

readLine 方法在 Java 1.7 中已被弃用;来自javadoc:

readLine()已弃用。此方法无法正确地将字节转换为字符。从 JDK 1.1 开始,读取文本行的首选方法是通过 BufferedReader.readLine() 方法。通过替换以下形式的代码,可以将使用 DataInputStream 类读取行的程序转换为使用 BufferedReader 类: DataInputStream d = new DataInputStream(in);

与: BufferedReader d = new BufferedReader(new InputStreamReader(in));

关于c# - 为什么 DataInputStream.readline 在字符串开头添加奇怪的字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11062046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com