简体   繁体   中英

How to consume, read and unzip a third party API response in ASP.Net MVC application

I am trying to consume a third party API whose URL looks like this:

https://api.crowdin.com/api/project/{PROJECT_NAME}/download/all.zip?key={MY_KEY}

This api returns a zip file as "all.zip" as response.

When I go to browser and make this request I get a all.zip file downloaded. Now I want to write C# code to get this result. Below is my attempt:

public async Task<ActionResult> Index()
        {
            var client = new HttpClient();
            client.BaseAddress = new Uri("https://api.crowdin.com/");
            HttpResponseMessage response = await client.GetAsync("api/project/{MY_PROJECT}/download/all.zip?key={MY_KEY}");
           // WHAT TO WRITE HERE
            return View();
        }

Question 1: I got the successful response and content type is application/zip , but now I don't know how to read this response.

Question 2: I want the response to unzipped and saved to a folder.

PS: The response .zip file is a collection of .resx File.

This is mostly from memory so I haven't tested the code. It should get you pretty close to what you're looking for:

Saving the response to file:

var response = httpClient.GetAsync("api/project/{MY_PROJECT}/download/all.zip?key={MY_KEY}");
using (var stream = await response.Content.ReadAsStreamAsync())
using (var fs = new FileStream(filename) {
    await stream.CopyToAsync(fs);
}

Unzipping the file (you could also do this in memory)

System.IO.Compression.ZipFile.ExtractToDirectory(filename, extractPath);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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