我需要调用Servlet调用,以使用C#自动化Java小程序。 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的文档,除了原始类型外,它将对象序列化。我知道字符串是类,那么它像对象或某些特殊情况一样序列化?

我尝试了一种解决方案,我在我的引用中导入了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)
有帮助吗?

解决方案 2

我终于必须让这个工作。

问题是在.NET中读取数据而不是使用StreamReader,我需要立即使用流对象。无论如何,只要在这里留在这里,以防万一它可以帮助他人解决问题:

错误代码:

List<byte> lByte = new List<byte>();
using (StreamReader sr = new StreamReader(myRequest.GetResponse().GetResponseStream()))
{
    while (sr.Peek() >= 0)
    {
        lByte.Add((byte)sr.Read());
    }
}

正确的代码:

byte[] buffer = new byte[1000];
using (Stream sr = myRequest.GetResponse().GetResponseStream())
{
    sr.Read(buffer, 0, 1000);
}

其他提示

如果您可以控制Java侧的序列化/避难所,则最好的选择是使用跨平台序列化协议,例如协议缓冲区。对于C ++,Java和Python:

http://code.google.com/p/protobuf/

对于.net,乔恩·斯基特(Jon Skeet)写了一个港口:

http://code.google.com/p/protobuf-net/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top