简体   繁体   English

无法从使用邮递员的网络API使用C#下载文件

[英]Not able to download file using C# from a web api which works using postman

I have recently started working with web api's. 我最近开始使用Web API。

I need to download a file in C# project from a web api, which works fine when I hit the web api using postman's send and download option. 我需要从Web api下载C#项目中的文件,当我使用邮递员的发送和下载选项访问Web api时,该文件工作正常。 Refer to the image, also please check the response in header's tab. 请参考图片,也请检查标题标签中的响应。 This way, I am able to directly download the file to my computer. 这样,我可以直接将文件下载到我的计算机上。

使用邮递员进行API呼叫

I want to do the same from my C# project, I found following two links which shows how to download a file from web api. 我想从我的C#项目中做同样的事情,发现以下两个链接显示了如何从Web api下载文件。

https://code.msdn.microsoft.com/HttpClient-Downloading-to-4cc138fd http://blogs.msdn.com/b/henrikn/archive/2012/02/16/downloading-a-google-map-to-local-file.aspx https://code.msdn.microsoft.com/HttpClient-Downloading-to-4cc138fd http://blogs.msdn.com/b/henrikn/archive/2012/02/16/downloading-a-google-map-to -local-file.aspx

I am using the following code in C# project to get the response: 我在C#项目中使用以下代码来获取响应:

 private static async Task FileDownloadAsync()
    {
        using (var client = new HttpClient())
        {

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Add("Accept", "text/html");
            try
            {
                // _address is exactly same which I use from postman
                HttpResponseMessage response = await client.GetAsync(_address);
                if (response.IsSuccessStatusCode)
                {
                }
                else
                {
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }

However I am not getting the response at all (before I can start to convert the response to a file), please check the error message coming: 但是,我根本没有得到响应(在我可以开始将响应转换为文件之前),请检查错误消息:

错误信息

What am I missing here, any help would be appreciated. 我在这里缺少什么,任何帮助将不胜感激。

As the (500s) error says - it's the Server that rejects the request. 正如(500s)错误所说-是服务器拒绝了请求。 The only thing I see that could cause an issues is the charset encoding. 我看到的唯一可能引起问题的是字符集编码。 Yours is the default UTF-8. 您的是默认的UTF-8。 You could try with other encodings. 您可以尝试使用其他编码。

Your request header says that you accept HTML responses only. 您的请求标头表示您仅接受HTML响应。 That could be a problem. 那可能是个问题。

Below method uses: 下面的方法使用:

  1. SSL certificate (comment out code for cert, if you don't use it) SSL证书(注释代码,如果不使用的话)
  2. Custom api header for additional layer of security (comment out Custom_Header_If_You_Need code, if you don't need that) 自定义api标头可提供额外的安全性(如果不需要,请注释出Custom_Header_If_You_Need代码)
  3. EnsureSuccessStatusCode will throw an error, when response is not 200. This error will be caught in and converted to a human readable string format to show on your screen (if you need to). 当响应不是200时,EnsureSuccessStatusCode将引发错误。该错误将被捕获并转换为人类可读的字符串格式以在屏幕上显示(如果需要)。 Again, comment it out if you don't need that. 同样,如果不需要的话,将其注释掉。

     private byte[] DownloadMediaMethod(string mediaId) { var cert = new X509Certificate2("Keystore/p12_keystore.p12", "p12_keystore_password"); var handler = new WebRequestHandler { ClientCertificates = { cert } }; using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("Custom_Header_If_You_Need", "Value_For_Custom_Header"); var httpResponse = client.GetAsync(new Uri($"https://my_api.my_company.com/api/v1/my_media_controller/{mediaId}")).Result; //Below one line is most relevant to this question, and will address your problem. Other code in this example if just to show the solution as a whole. var result = httpResponse.Content.ReadAsByteArrayAsync().Result; try { httpResponse.EnsureSuccessStatusCode(); } catch (Exception ex) { if (result == null || result.Length == 0) throw; using (var ms = new MemoryStream(result)) { var sr = new StreamReader(ms); throw new Exception(sr.ReadToEnd(), ex); } } return result; } } 

Once you have your http response 200, you can use the received bytes[] as under to save them in a file: 获得http响应200后,您可以按以下方式使用接收到的bytes []将它们保存到文件中:

using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
    fs.Write(content, 0, content.Length);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM