【问题标题】:What is an alternative of System.Net.WebClient.UploadString in System.Net.Http.HttpClient namespace for WinRT?WinRT 的 System.Net.Http.HttpClient 命名空间中 System.Net.WebClient.UploadString 的替代方法是什么?
【发布时间】:2013-01-04 16:59:18
【问题描述】:

我正在将应用程序从 WPF 移植到 Windows 8 应用程序。

我想知道System.Net.Http.HttpClient 命名空间中是否有类似System.Net.WebClient.UploadString 的功能(因为System.Net.WebClientWinRT 中不可用)如果是,非常感谢一个示例!如果没有,还有其他选择吗?

在旁注中,在 Morten Nielsen 的帮助下,我能够使用 System.Net.Http.HttpClient 命名空间将 WebClient.DownloadString 转换为等价物 http://www.sharpgis.net/post/2011/10/05/WinRT-vs-Silverlight-Part-7-Making-WebRequests.aspx

【问题讨论】:

    标签: .net network-programming windows-runtime httpclient webclient


    【解决方案1】:

    是的,您将使用PostAsync method

    该方法采用Uri 或字符串(就像WebClient 类中的UploadString method)以及HttpContent instance

    HttpContent 实例与不同类型的内容无关,允许您不仅指定提供内容的机制(ByteArrayContent 用于字节数组,StreamContent 用于@987654327 @ 等),但结构也是如此(MultipartFormDataContent)。

    也就是说,还有一个StringContent class 将发送字符串,如下所示:

    // 内容。 string post = "你要发布的内容";

    // The client.
    using (client = new HttpClient());
    {
        // Post.
        // Let's assume you're in an async method.
        HttpResponseMessage response = await client.Post(
            "http://yourdomain/post", new StringContent(post));
    
        // Do something with the response.
    }
    

    如果您需要指定Encodingthere's a constructor that takes an Encoding,您可以这样使用:

    // The client.
    using (client = new HttpClient());
    {
        // Post.
        // Let's assume you're in an async method.
        HttpResponseMessage response = await client.Post(
            "http://yourdomain/post", new StringContent(post),
             Encoding.ASCII);
    
        // Do something with the response.
    }
    

    从那里开始,在发送响应时处理HttpResponseMessage(如果这对您很重要,如果它不是单向操作)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-09
      • 1970-01-01
      • 1970-01-01
      • 2014-11-02
      • 1970-01-01
      • 2011-06-26
      • 2019-09-27
      • 2015-12-19
      相关资源
      最近更新 更多