我正在使用Protobuf-net尝试将序列化对象发送到我正在另一个项目中运行的web应用程序。 Serializer.Serialize<T>()
方法接受Stream(写入)和T的实例(在这种情况下,我设置为使用protobuf-net的几个对象的列表)
我该怎么做呢?我是否需要写入文件或者我可以以某种方式将该流作为postdata发送?下面你可以看到我使用字符串作为postdata。
我的执行帖子方法
public static void ExecuteHttpWebPostRequest(Uri uri,string postdata, int requestTimeOut, ref string responseContent)
{
if (string.IsNullOrEmpty(uri.Host))// || !IsConnectedToInternet(uri))
return;
var httpWebReq = (HttpWebRequest)WebRequest.Create(uri);
var bytePostData = Encoding.UTF8.GetBytes(postdata);
httpWebReq.Timeout = requestTimeOut*1000;
httpWebReq.Method = "POST";
httpWebReq.ContentLength = bytePostData.Length;
//httpWebReq.ContentType = "text/xml;charset=utf-8";
httpWebReq.ContentType = "application/octet-stream";
//httpWebReq.TransferEncoding=
//httpWebReq.ContentType = "application/xml";
//httpWebReq.Accept = "application/xml";
var dataStream = httpWebReq.GetRequestStream();
dataStream.Write(bytePostData, 0, bytePostData.Length);
dataStream.Close();
var httpWebResponse = (HttpWebResponse)httpWebReq.GetResponse();
// Get the stream associated with the response.
var receiveStream = httpWebResponse.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
var readStream = new StreamReader(receiveStream,Encoding.Default);
responseContent = readStream.ReadToEnd();
httpWebResponse.Close();
}
答案 0 :(得分:1)
您只需将序列化为请求:
Serializer.Serialize(dataStream, obj);
同样,如果您愿意,可以从receiveStream
反序列化。
但是,请注意,protobuf数据不是文本,不应该被视为这样 - 如果你尝试的话会发生非常糟糕的事情。