I'm attempting to utilize an API call that I found in some Python code and translate it into C# so that I can integrate it into a Unity application I'm developing. The Python code is:
response = requests.request(
method=method,
url=url.as_uri(),
verify=settings.CACERT_FILE,
**kwargs,
)
where Method = POST, Verify = None, and Kwargs = {'json': {'time': 1, 'types': ['the_types']}}.
My C# implementation:
var client = new HttpClient();
client.BaseAddress = new Uri("theurl.com");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("{'json': {'time': 1, 'types': ['the_types']}}").Result;
if (response.IsSuccessStatusCode)
{
Debug.Log("Worked");
}
else
{
Debug.Log("Didn't work");
}
client.Dispose();
I'm quite new to C#, and I can't figure out what I'm missing or where to go from here. Thanks in advance!
EDIT: Utilizing client.PostAsync
HttpResponseMessage response = client.PostAsync(new Uri("theUrl"), new StringContent("{'json': {'time': 1, 'types': ['the_types']}}")).GetAwaiter().GetResult();
I think this example perfectly suites your request. You can easily change HttpMethod or request content in it.
using var httpClient = new HttpClient();
var message = new HttpRequestMessage(HttpMethod.Post, "your url");
message.Content = JsonContent.Create("your json content", new MediaTypeHeaderValue("application/json"));
var response = await httpClient.SendAsync(message);
if (response.IsSuccessStatusCode)
{
// ...
}
Also dont forget to await
your asynchronous code (client.PostAsync
in your example or httpClient.SendAsync
in mine).
Also good to mention that best practice is to use IHttpClientFactory
with custom options such a "baseUrl" or "required headers" for HttpClient declaration.