1

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()
1
  • Which part of the "conversion" is giving you trouble? Have you tried first and how does you attempt look? Commented Jul 29, 2022 at 20:14

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.