Home > Mobile >  How to convert HttpWebRequest with POST method of a legacy program to HttpClient, using c#?
How to convert HttpWebRequest with POST method of a legacy program to HttpClient, using c#?

Time:07-30

I have legacy code that uses HttpWebRequest and it works fine. Microsoft suggests that we use HttpClient. How can I modify it to use HttpClient, in c#?

string authText = "{   "AuthParams":{      "AuthToken":"TokenID",      "FirmID":"MSFT",      "SystemID":"Systems-Internal",      "Version":"1.0",      "UUID":"SystemsInternalAPIUser"   }}";
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://msft.com/api/busnWebService/xbox-games");
JObject data = JObject.Parse(authText);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    streamWriter.Write(data);
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

var streamReader = new StreamReader(httpResponse.GetResponseStream());
string responseText = streamReader?.ReadToEnd();

(JsonConvert.DeserializeObject<CompRoot>(responseText).Data)
.Select(t => new CompanyClass
{       
    Ticker = t.Ticker,      
}).ToList()

CodePudding user response:

Since I can not try the solution with your payload and endpoint, something like the following should solve the problem without testing it.

string authText = "{\"AuthParams\":{\"AuthToken\":\"TokenID\",\"FirmID\":\"MSFT\",\"SystemID\":\"Systems - Internal\",\"Version\":\"1.0\",\"UUID\":\"SystemsInternalAPIUser\"}}";
var content = new StringContent(authText, Encoding.UTF8, "application/json");
using HttpClient client = new HttpClient();
var httpResponse = await client.PostAsync("http://msft.com/api/busnWebService/xbox-games", content);

string responseText = await httpResponse.Content.ReadAsStringAsync();

With HttpClinet you need to use async Task with await. I assume your mapping from the response should be the same. But you need to validate that.

  • Related