0

I have an API using POST Method.From this API I can download the file via Postmen tool.But I would like to know how to download file from C# Code.I have tried below code but POST Method is not allowed to download the file.

Code:-

 using (var client = new WebClient())
            {
                
                client.Headers.Add("X-Cleartax-Auth-Token", ConfigurationManager.AppSettings["auth-token"]);
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                string url = ConfigurationManager.AppSettings["host"] + ConfigurationManager.AppSettings["taxable_entities"] + "/ewaybill/download?print_type=detailed";
                TransId Id = new TransId()
                {
                    id = TblHeader.Rows[0]["id"].ToString()
                };

                List<string> ids = new List<string>();

                ids.Add(TblHeader.Rows[0]["id"].ToString());

                string DATA = JsonConvert.SerializeObject(ids, Newtonsoft.Json.Formatting.Indented);
                string res = client.UploadString(url, "POST",DATA);
                client.DownloadFile(url, ConfigurationManager.AppSettings["InvoicePath"].ToString() + CboGatePassNo.EditValue.ToString().Replace("/", "-") + ".pdf");
            }

Postmen Tool:-

URL : https://ewbbackend-preprodpub-http.internal.cleartax.co/gst/v0.1/taxable_entities/1c74ddd2-6383-4f4b-a7a5-007ddd08f9ea/ewaybill/download?print_type=detailed

Header :-

Content-Type : application/json
X-Cleartax-Auth-Token :b1f57327-96db-4829-97cf-2f3a59a3a548

Body :-

[
    "GLD24449"
]
Packing
  • 17
  • 7
  • This [thread](https://stackoverflow.com/questions/39010572/use-webclient-to-post-query-and-download-file) may help – talesa82035 Nov 26 '20 at 06:46
  • Thanks for reply,As per my above code what to be pass "data" which you provide me example code – Packing Nov 26 '20 at 07:13
  • please see my api parameter which is working fine in postmen but i would like to run the same as in C# Code – Packing Nov 26 '20 at 07:21

2 Answers2

0

using (WebClient client = new WebClient())
  {
    client.Headers.Add("X-Cleartax-Auth-Token", ConfigurationManager.AppSettings["auth-token"]);
    client.Headers[HttpRequestHeader.ContentType] = "application/json";
    string url = ConfigurationManager.AppSettings["host"] + ConfigurationManager.AppSettings["taxable_entities"] + "/ewaybill/download?print_type=detailed";
    client.Encoding = Encoding.UTF8;

    //var data = "[\"GLD24449\"]";
    var data = UTF8Encoding.UTF8.GetBytes(TblHeader.Rows[0]["id"].ToString());
    byte[] r = client.UploadData(url, data);
    using (var stream = System.IO.File.Create("FilePath"))
    {
      stream.Write(r,0,r.length);
    }
  }

Try this. Remember to change the filepath. Since the data you posted is not valid json. So, I decide to post data this way.

talesa82035
  • 124
  • 5
0

I think it's straight forward, but instead of using WebClient, you can use HttpClient, it's better.
here is the answer HTTP client for downloading -> Download file with WebClient or HttpClient?
comparison between the HTTP client and web client-> Deciding between HttpClient and WebClient
Example Using WebClient

 public static void Main(string[] args)
    {
        string path = @"download.pdf";

        // Delete the file if it exists.
        if (File.Exists(path))
        {
            File.Delete(path);
        }

        var uri = new Uri("https://ewbbackend-preprodpub-http.internal.cleartax.co/gst/v0.1/taxable_entities/1c74ddd2-6383-4f4b-a7a5-007ddd08f9ea/ewaybill/download?print_type=detailed");
        WebClient client = new WebClient();
        client.Headers[HttpRequestHeader.ContentType] = "application/json";
        client.Headers.Add("X-Cleartax-Auth-Token", "b1f57327-96db-4829-97cf-2f3a59a3a548");
        client.Encoding = Encoding.UTF8;
        var data = UTF8Encoding.UTF8.GetBytes("[\"GLD24449\"]");
        byte[] r = client.UploadData(uri, data);
        using (var stream = System.IO.File.Create(path))
        {
            stream.Write(r, 0, r.Length);
        }
    }


Here is the sample code, don't forget to change the path.

public class Program
{
    public static async Task Main(string[] args)
    {
        string path = @"download.pdf";

        // Delete the file if it exists.
        if (File.Exists(path))
        {
            File.Delete(path);
        }

        var uri = new Uri("https://ewbbackend-preprodpub-http.internal.cleartax.co/gst/v0.1/taxable_entities/1c74ddd2-6383-4f4b-a7a5-007ddd08f9ea/ewaybill/download?print_type=detailed");
        HttpClient client = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Post, uri)
        {
            Content = new StringContent("[\"GLD24449\"]", Encoding.UTF8, "application/json")
        };
        request.Headers.Add("X-Cleartax-Auth-Token", "b1f57327-96db-4829-97cf-2f3a59a3a548");
        var response = await client.SendAsync(request);
        if (response.IsSuccessStatusCode)
        {
            using (FileStream fs = File.Create(path))
            {
                await response.Content.CopyToAsync(fs);
            }
        }
        else 
        {
        }
    }
Manish
  • 1,139
  • 7
  • 21
  • Thanks for providing code,but await is not supported in my current version of visual studio..please advise the alternate solution using webclient. – Packing Nov 26 '20 at 14:50