Cannot download a pdf with RestSharp?

我怕爱的太早我们不能终老 提交于 2021-02-07 13:20:29

问题


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.


回答1:


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);


来源:https://stackoverflow.com/questions/47099705/cannot-download-a-pdf-with-restsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!