0

从 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.
如果可能的话,我真的很想以更好的方式做到这一点

*更新添加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";
}
4

2 回答 2

2

在 Java 1.7 中不推荐使用 readLine 方法;来自javadocs:

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

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

于 2012-06-16T08:58:17.070 回答
2

三个初始字节是 UTF8 BOM(字节排序标记)。您将需要告诉您的 Java 代码使用相同的编码。

于 2012-06-16T09:02:14.120 回答