简体   繁体   English

如何在Windows Phone 8中序列化HttpClient对象?

[英]How serialize HttpClient Object in windows phone 8?

I use System.Net.Http.HttpClient Object to login to a forum successfully and do many operations. 我使用System.Net.Http.HttpClient对象成功登录到论坛并执行许多操作。 Then the object may have some state, so I want to reuse the object when the program is been opened again, implementing the automatic login. 然后该对象可能具有某种状态,因此我想在再次打开程序时重用该对象,以实现自动登录。 I use Json.net to serialize the HttpClient Object to the IsolatedStorage, but not available. 我使用Json.net将HttpClient对象序列化为IsolatedStorage,但不可用。 Can somebody help me? 有人可以帮我吗? Thank you!! 谢谢!!

//The code for initializing the HttpClient Object
HttpClientHandler handler = new HttpClientHandler();
handler.UseCookies = true;
HttpCliclient = new HttpClient(handler);

I first serialize the object using Json.net, get the json string: {"DefaultRequestHeaders":],"BaseAddress":null,"Timeout":"00:01:40","MaxResponseContentBufferSize":2147483647} 我首先使用Json.net序列化对象,获取json字符串:{“ DefaultRequestHeaders”:],“ BaseAddress”:null,“ Timeout”:“ 00:01:40”,“ MaxResponseContentBufferSize”:2147483647}

Then deserialize the json string to get the object, but the object need logining again to do operations. 然后反序列化json字符串以获取对象,但是该对象需要再次登录才能执行操作。

        using (IsolatedStorageFile storeFolder = IsolatedStorageFile.GetUserStoreForApplication()) {
            string jsonData = JsonConvert.SerializeObject(httpclient);
            System.Diagnostics.Debug.WriteLine(jsonData);
            using (IsolatedStorageFileStream stream = storeFolder.CreateFile(path))
            using (StreamWriter writer = new StreamWriter(stream))
                writer.Write(jsonData);
        }


        using (IsolatedStorageFile storeFolder = IsolatedStorageFile.GetUserStoreForApplication()) {
            string jsonData;
            using (IsolatedStorageFileStream stream = storeFolder.OpenFile(path, FileMode.Open))
            using (StreamReader reader = new StreamReader(stream))
                jsonData = reader.ReadToEnd();

            HttpClient httpclient = JsonConvert.DeserializeObject<HttpClient>(jsonData);
            //need login again to do some operations
        }

Don't try and serialize HttpClient. 不要尝试序列化HttpClient。 The chances of it working are highly unlikely. 它工作的可能性极小。 Pretty much the only state you might be able to serialize from it are the default request headers. 您可能可以从中进行序列化的唯一状态是默认请求标头。 Create a HttpClient Factory method and just serialize out the header information that you want to preserve. 创建一个HttpClient Factory方法,然后序列化要保留的标头信息。

Refer to this link for an example. 请参考此链接以获取示例。 One of the best ways for implementing API Client on both WP8 and Metro Applications. 在WP8和Metro应用程序上实现API客户端的最佳方法之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM