2013-06-18 39 views
0

中使用protobuf-net進行序列化我正在使用Protobuf-net嘗試將序列化對象發送到我正在另一個項目中運行的Web應用程序。 Serializer.Serialize<T>()方法需要流(寫入)和T的實例(在這種情況下,我設置了與protobuf-net一起使用的一些對象的列表)使用protobuf-net進行序列化並在http

我該如何去做這件事?我需要寫入文件還是可以以某種方式將數據流作爲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(); 

    } 

回答

1

您可以只序列化請求

Serializer.Serialize(dataStream, obj); 

,同樣,你可以從receiveStream反序列化,如果你選擇。

但是,請注意,protobuf數據不是文本,不應該這樣對待 - 如果您嘗試這樣做會發生非常糟糕的事情。

相關問題