【问题标题】:How serialize HttpClient Object in windows phone 8?windows phone 8中如何序列化HttpClient对象?
【发布时间】:2014-03-20 13:26:53
【问题描述】:

我使用 System.Net.Http.HttpClient 对象成功登录论坛并进行了许多操作。那么对象可能有一些状态,所以我想在程序再次打开时重用对象,实现自动登录。 我使用Json.net 将HttpClient 对象序列化到IsolatedStorage,但不可用。 有人可以帮助我吗?谢谢!!

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

我先用Json.net序列化对象,得到json字符串: {"DefaultRequestHeaders":],"BaseAddress":null,"Timeout":"00:01:40","MaxResponseContentBufferSize":2147483647}

然后反序列化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
        }

【问题讨论】:

  • 那么存储登录对象或json序列化的问题在哪里?
  • 我反序列化了json字符串来获取对象,但是对象需要重新登录才能进行操作。上面添加了序列化/反序列化代码。谢谢!

标签: c# serialization windows-phone-8 login dotnet-httpclient


【解决方案1】:

不要尝试序列化 HttpClient。它发挥作用的可能性极小。您可能能够从中序列化的唯一状态几乎是默认请求标头。创建一个 HttpClient Factory 方法并序列化出您想要保留的标头信息。

【讨论】:

  • 谢谢!米勒先生!我明白你的意思。所以我保留了登录的头部信息,但是头部包含验证码内容,我不想每次都重新输入验证码,因为验证码一旦使用,下次就不能使用了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
  • 2014-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多