将 WebClient 转换为 HttpClient

Converting WebClient to HttpClient

我已经上网冲浪并为此工作了几个小时,我读到要扔掉我的电脑。

我在 WPF 应用程序上有一个 WebClient,需要转换为 UWP 应用程序的 HttpClient。我遇到了很多 header 错误,而且由于我不是网络专家,所以我在自责。

这是原文,如果有人非常好心帮我把它转换成 HttpClient,我将不胜感激。

using (var client = new WebClient())
{
    string request = "------WebKitFormBoundarygWsJMIUcbjwBPfeL"
                    + Environment.NewLine
                    + "Content-Disposition: form-data; name=\"guid\""
                    + Environment.NewLine
                    + Environment.NewLine
                    + presetSmall.PresetId.ToString()
                    + Environment.NewLine
                    + "------WebKitFormBoundarygWsJMIUcbjwBPfeL"
                    + Environment.NewLine
                    + "Content-Disposition: form-data; name=\"delay\""
                    + Environment.NewLine
                    + Environment.NewLine
                    + "0"
                    + Environment.NewLine
                    + "------WebKitFormBoundarygWsJMIUcbjwBPfeL--"
                    + Environment.NewLine;

    client.Headers.Add(HttpRequestHeader.ContentType, "multipart/form-data; boundary=----WebKitFormBoundarygWsJMIUcbjwBPfeL");

    client.UploadStringAsync(new Uri(ServerName + UriForPresetExecution), "POST", request);

}

问题出在 client.Headers.Add 方法中...为了时间的缘故,我无法弄清楚 HttpClient 要我如何添加那些 header。

请试试这个:

using System.Net.Http;
using System.Net.Http.Headers;

using (var httpClient = new HttpClient()) 
{ 
    var httpContent = new StringContent(request); 
    httpContent.Headers.Clear(); 
    httpContent.Headers.Add("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundarygWsJMIUcbjwBPfeL"); 
    var response = await httpClient.PostAsync(requestUri, httpContent); 
}