I'm making a C# script (.NET app) to consume an API and retrieve data (a zip file) from server, then save the downloaded zip file to disk in a temporary directory.
I can download the zip file from a Rest client like Postman by clicking on "Save and Download" but I'm facing a problem to download it and save it to disk using my C# script,
I've tried to execute the following C# script, but it only retrieves JSON response, when I change the Content-Type to "application/zip" I receive an error 415 unsupported Media Type
here's a part of my C# code:
class Program
{
static void Main(string[] args)
{
var tokenData = GetJson(tokenUrl, null, body);
if(tokenData == null)
Environment.Exit(0);
//
// Request document sets using OData
// =========================
string accessToken = tokenData.access_token;
string odataUrl = innovatorUrl + "/server/odata/ACT_Document Set('D71DC18B35764C509F3565F511DFFF20')/act_reqtify_project_file/$value";
var documentset = GetJson(odataUrl, accessToken);
Console.WriteLine(documentset);
}
static dynamic GetJson( string url, string accessToken = null, HttpContent body = null )
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/zip") );
if(accessToken != null)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
HttpResponseMessage response;
if (body == null)
{
response = client.GetAsync(url).Result;
}
else
{
response = client.PostAsync(url, body).Result;
}
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsAsync<dynamic>().Result;
}
else
{
Console.WriteLine("{0}: {1} ({2})", url, (int)response.StatusCode, response.ReasonPhrase);
return null;
}
}
}
static string GetOAuthServerUrl( string url )
{
var discovery = GetJson(url);
return discovery?.locations[0]?.uri;
}
static string GetTokenEndpoint(string url)
{
var configuration = GetJson(url);
return configuration?.token_endpoint;
}
}
Problem: When my script is executed I receive this error 415 (Unsupported Media Type):
Need: To be able to download the zip file received from the api and to save it to disk
any help with this issue please?
Thank you in advance,
The HTTP 415 Unsupported Media Type client error response code indicates that the server has refused to accept the client request due to an supported payload format.
You should check and match the headers present inside postman. Also try to read response as a byte array. Here is a quick code snippet that you can refer:
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = client.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
byte[] zipFileData = await response.Content.ReadAsByteArrayAsync();
// Save the zip file to disk
File.WriteAllBytes("output.zip", zipFileData);
}
else
{
Console.WriteLine("{0}: {1} ({2})", url, (int)response.StatusCode, response.ReasonPhrase);
return null;
}
}