Michael Puckett II
Michael Puckett II

Reputation: 6749

Converting WebClient to HttpClient

I have been surfing and working on this for hours now and I'm read to throw my PC.

I have a WebClient on WPF application that needs to be converted to HttpClient for UWP application. I am getting a lot of header errors and since I'm not a web guru I am beating myself.

Here's the original and if someone would be extremely kind and help me convert it to HttpClient I would be very thankful.

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);

}

The problem is in the client.Headers.Add method... I cannot for the sake of time figure out how HttpClient wants me to add those headers.

Upvotes: 3

Views: 1178

Answers (1)

kennyzx
kennyzx

Reputation: 12993

Please try this:

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); 
} 

Upvotes: 3

Related Questions