我需要使用c#为Java applet的自动化调用servlet调用。 Java小程序使用URL连接对象调用servlet。
URL servlet = new URL(servletProtocol, servletHost, servletPort, "/" + ServletName);
URLConnection con = servlet.openConnection();
con.setDoOutput(true);
ObjectOutputStream out = new ObjectOutputStream(con.getOutputStream());
// Write several parameters strings
out.writeObject(param[0]);
out.writeObject(param[1]);
out.flush();
out.close();
问题是我需要使用c#模拟它。我相信对应对象将是HttpWebRequest
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(servletPath);
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(param[0],0,param[0].length);
newStream.Write(param[1],0,param[1].length);
newStream.Close();
如何将字符串写为序列化的Java字符串?这里有什么解决方法吗?根据Java中ObjectOutputStream的文档,它将序列化对象(原始类型除外)。我知道String是类,所以它像对象或某些特殊情况一样序列化吗?
我尝试了一种解决方案,在我的参考文献中导入了IKVM(http://www.ikvm.net/)Java虚拟机,并试图在Java中使用java.io库。不幸的是,当调用ObjectInputStream构造函数时,将引发“无效的流头”。
这是我修改后的代码:
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
List<byte> lByte = new List<byte>();
using (StreamReader sr = new StreamReader(myRequest.GetResponse().GetResponseStream()))
{
while (sr.Peek() >= 0)
{
lByte.Add((byte)sr.Read());
}
}
byte[] bArr = lByte.ToArray();
ObjectInputStream inputStream = null;
try
{
//Construct the ObjectInputStream object
inputStream = new ObjectInputStream(new ByteArrayInputStream(bArr));
Object obj = null;
while ((obj = inputStream.readObject()) != null)
{
string objStr = obj as string;
}
}
catch (java.lang.Exception ex)
最佳答案
如果您可以控制Java方面的序列化/反序列化,那么最好的选择是使用跨平台序列化协议,例如Protocol Buffers。对于C ++,Java和Python:
http://code.google.com/p/protobuf/
对于.NET,Jon Skeet编写了一个端口:
http://code.google.com/p/protobuf-net/