C
C#4mo ago
konedi

Anyone know what is up with HttpClient failing Post request?

I am making a post request to a cloudflare ai worker and HttpClient can't seem to succeed. I tried other rest clients, javascript,python and including RestSharp and it works. Here is the code:
byte[] buffer = await File.ReadAllBytesAsync(image_path);

// Create the input data object
var inputData = new
{
image = buffer.Select(x => (int)x).ToArray(),
prompt = "this is a video game screenshot, describe the environment and atmosphere",
max_tokens = 256
};

// Serialize the input data to JSON
string jsonString = JsonSerializer.Serialize(inputData);

// Create an HttpClient instance
using (HttpClient httpClient = new HttpClient())
{
// Set up the request headers
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", api_key);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));

// Prepare the content for the request
var content = new StringContent(jsonString, null, "application/json");

try
{
// Send the POST request
HttpResponseMessage response = await httpClient.PostAsync(url, content);

// Check the response
if (response.IsSuccessStatusCode)
{
string responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
else
{
Console.WriteLine($"Error: {response.StatusCode}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
}
byte[] buffer = await File.ReadAllBytesAsync(image_path);

// Create the input data object
var inputData = new
{
image = buffer.Select(x => (int)x).ToArray(),
prompt = "this is a video game screenshot, describe the environment and atmosphere",
max_tokens = 256
};

// Serialize the input data to JSON
string jsonString = JsonSerializer.Serialize(inputData);

// Create an HttpClient instance
using (HttpClient httpClient = new HttpClient())
{
// Set up the request headers
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", api_key);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));

// Prepare the content for the request
var content = new StringContent(jsonString, null, "application/json");

try
{
// Send the POST request
HttpResponseMessage response = await httpClient.PostAsync(url, content);

// Check the response
if (response.IsSuccessStatusCode)
{
string responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
else
{
Console.WriteLine($"Error: {response.StatusCode}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
}
12 Replies
Sossenbinder
Sossenbinder4mo ago
Well, what's the error? There are a few bits of suboptimal httpclient usage in here, but that shouldn't affect the issue
konedi
konediOP4mo ago
error is just a 400 status code and some json schema validation failing on the cloudflare side: {"errors":[{"message":"AiError: Bad input: must be string, must have required property 'image', must be number, must match exactly one schema in oneOf","code":5006}],"success":false,"result":{},"messages":[]} same request works everywhere else. Something with the underlying httpclient request pipeline if I had to guess, but haven't been able to figure it out: Here is the same request with RestSharp:
var inputData = new
{
image = buffer.Select(x => (int)x).ToArray(),
prompt = "this is a video game screenshot, describe the environment and atmosphere",
max_tokens = 256
};

var jsonString = JsonSerializer.Serialize(inputData);

var client = new RestClient();
var request = new RestRequest(url, Method.Post);

request.AddHeader("Authorization", $"Bearer {api_key}");
request.AddHeader("Content-Type", "application/json");
request.AddJsonBody(jsonString);

try
{
var response = await client.ExecuteAsync(request);

if (response.IsSuccessful)
{
Console.WriteLine(response.Content);
}
else
{
Console.WriteLine($"Error: {response.ErrorMessage}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
var inputData = new
{
image = buffer.Select(x => (int)x).ToArray(),
prompt = "this is a video game screenshot, describe the environment and atmosphere",
max_tokens = 256
};

var jsonString = JsonSerializer.Serialize(inputData);

var client = new RestClient();
var request = new RestRequest(url, Method.Post);

request.AddHeader("Authorization", $"Bearer {api_key}");
request.AddHeader("Content-Type", "application/json");
request.AddJsonBody(jsonString);

try
{
var response = await client.ExecuteAsync(request);

if (response.IsSuccessful)
{
Console.WriteLine(response.Content);
}
else
{
Console.WriteLine($"Error: {response.ErrorMessage}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
Cracker
Cracker4mo ago
use same headers for HttpClient where you used for RestClient then
Omnissiah
Omnissiah4mo ago
in these cases what i would do is examine the differences between a request that works and the one that doesn't with fiddler or wireshark or what have you
Cracker
Cracker4mo ago
serialized payload looks same, only difference is headers
Sossenbinder
Sossenbinder4mo ago
I'm not big on Restsharp but I ran these against a mock server
Sossenbinder
Sossenbinder4mo ago
Restsharp
No description
Sossenbinder
Sossenbinder4mo ago
HttpClient
No description
Sossenbinder
Sossenbinder4mo ago
Maybe that already helps. Not sure how strict your endpoint is on certain headers
Sossenbinder
Sossenbinder4mo ago
Use IHttpClientFactory to implement resilient HTTP requests - .NET
Learn how to use IHttpClientFactory, available since .NET Core 2.1, for creating HttpClient instances, making it easy for you to use it in your applications.
konedi
konediOP4mo ago
Thank you, so it just looks like the HttpClient doesn't have the necessary headers. This is a cloudflare Rest API endpoint btw, so it seems like they are really strict. I just don't understand why HttpClient wouldn't have all the default headers and every other program does(python, js, thunderclient(rest client)). if I had to guess, it's gotta be the Accept-encoding header. I'll check that out. It turned out to be the charset=utf-8.... I spent hours on this and did not expect the default content-type application/json that comes with charset=utf-8 to be the issue... sigh I even set the encoding to null on the StringContent object... closing now. Thank you all.
Sossenbinder
Sossenbinder4mo ago
Yep, Content-Type for your request, Accept Headers for what you accept as a response from the server
Want results from more Discord servers?
Add your server