WinRT的System.Net.Http.HttpClient命名空间中System.Net.WebClient.UploadString的替代方法是什么?

时间:2013-01-04 16:59:19

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

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

我想知道System.Net.WebClient.UploadString命名空间中是否存在System.Net.Http.HttpClient类似的功能(因为System.Net.WebClientWinRT不可用)如果是,示例是非常感激!如果没有,有没有替代方案?

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

1 个答案:

答案 0 :(得分:1)

是的,您可以使用PostAsync method

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

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

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

//内容。 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.
}

如果您需要指定一个StringContent classEncoding,您可以这样使用:

// 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.
}

从那里开始,当发送响应时,问题是处理there's a constructor that takes an Encoding(如果这对你很重要,如果它不是单向操作)。