Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot download a pdf with RestSharp?

I have been struggling to download a simple pdf hosted online using restsharp. I have been playing around with the code for over an hour and all I get are null object results.

The file downloads easily in POSTMAN using a GET and no content header set but still what gives?

Below is the noddy sandbox test I have been experimenting around with:

[TestFixture]
public class Sandbox
{
    [Test]
    public void Test()
    {
        var uri = "https://www.nlm.nih.gov/mesh/2018/download/2018NewMeShHeadings.pdf";
        var client = new RestClient();
        var request = new RestRequest(uri, Method.GET);
        //request.AddHeader("Content-Type", "application/octet-stream");
        byte[] response = client.DownloadData(request);
        File.WriteAllBytes(@"C:\temp\1.pdf", response);
    }
}

Update: Return a Stream

        var baseUri = "https://www.nlm.nih.gov/mesh/2018/download/";
        var client = new RestClient(baseUri);
        var request = new RestRequest("2018NewMeShHeadings.pdf", Method.GET);
        request.AddHeader("Content-Type", "application/octet-stream");
        var tempFile = Path.GetTempFileName();
        var stream = File.Create(tempFile, 1024, FileOptions.DeleteOnClose);
        request.ResponseWriter = responseStream => responseStream.CopyTo(stream);
        var response = client.DownloadData(request);

The stream is now populated with the downloaded data.

like image 730
IbrarMumtaz Avatar asked Nov 03 '17 15:11

IbrarMumtaz


People also ask

What is RestSharp DLL?

RestSharp is a comprehensive, open-source HTTP client library that works with all kinds of DotNet technologies. It can be used to build robust applications by making it easy to interface with public APIs and quickly access data without the complexity of dealing with raw HTTP requests.


1 Answers

Try this:

    var uri = "https://www.nlm.nih.gov/mesh/2018/download/";
    var client = new RestClient(uri);
    var request = new RestRequest("2018NewMeShHeadings.pdf", Method.GET);
    //request.AddHeader("Content-Type", "application/octet-stream");
    byte[] response = client.DownloadData(request);
like image 200
Yuri S Avatar answered Oct 05 '22 02:10

Yuri S