我正在制作一个 C# 脚本(.NET 应用程序)来使用 API 并从服务器检索数据(zip 文件),然后将下载的 zip 文件保存到磁盘的临时目录中。
我可以通过单击“保存并下载”从 Postman 等 Rest 客户端下载 zip 文件,但我在使用 C# 脚本下载它并将其保存到磁盘时遇到问题,
我尝试执行以下 C# 脚本,但它只检索 JSON 响应,当我将 Content-Type 更改为“application/zip”时,我收到错误 415 不支持的媒体类型
这是我的 C# 代码的一部分:
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;
}
}
问题:执行我的脚本时,收到此错误 415(不支持的媒体类型):
需要:能够下载从 api 收到的 zip 文件并将其保存到磁盘
这个问题有什么帮助吗?
提前谢谢您,
HTTP 415 Unsupported Media Type客户端错误响应代码表示服务器由于受支持的有效负载格式而拒绝接受客户端请求。
您应该检查并匹配邮递员中存在的标头。还尝试将响应读取为字节数组。这是一个快速代码片段,您可以参考:
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;
}
}