0
点赞
收藏
分享

微信扫一扫

212-c# url下载pdf,url请求,有参数,且携带cookies

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        // 设置要下载的PDF文件的URL
        string pdfUrl = "https://example.com/path/to/your/pdf.pdf"; // 替换成实际的PDF文件URL

        // 创建一个 HttpClient 实例,并配置 CookieContainer 以管理 Cookies
        var cookieContainer = new CookieContainer();
        var handler = new HttpClientHandler
        {
            CookieContainer = cookieContainer,
            UseCookies = true
        };

        using (HttpClient httpClient = new HttpClient(handler))
        {
            // 设置要传递的 Cookies(可选)
            var cookies = new CookieCollection
            {
                new Cookie("CookieName1", "CookieValue1", "/", "example.com"), // 替换成实际的Cookie信息
                new Cookie("CookieName2", "CookieValue2", "/", "example.com")
                // 添加其他的 Cookies(如果有的话)
            };
            cookieContainer.Add(cookies);

            // 构建请求参数
            var requestParams = new
            {
                YzpzzlDm = "BDA0611159",
                Skssqq = "2023-01-01",
                Skssqz = "2023-03-31",
                Sbuuid = "6F9F1043B95773DD6160C7EE0893BA8C",
                Pzxh = "10015123000019800167",
                Bbids = new string[] { }
            };

            // 使用 Newtonsoft.Json 库将参数对象转换为 JSON 字符串
            string jsonParams = Newtonsoft.Json.JsonConvert.SerializeObject(requestParams);

            // 创建 HTTP 请求的内容
            var content = new StringContent(jsonParams, System.Text.Encoding.UTF8, "application/json");

            try
            {
                // 使用 Task.Run 在后台线程执行下载操作
                Task.Run(async () =>
                {
                    // 发送 POST 请求,传递参数
                    HttpResponseMessage response = await httpClient.PostAsync(pdfUrl, content);

                    // 检查响应是否成功
                    if (response.IsSuccessStatusCode)
                    {
                        // 读取响应内容作为字节数组
                        byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();

                        // 将 PDF 字节数组保存到本地文件
                        string localFilePath = "downloaded.pdf"; // 替换为你想要保存的本地文件路径
                        System.IO.File.WriteAllBytes(localFilePath, pdfBytes);

                        Console.WriteLine("PDF文件已成功下载到:" + localFilePath);
                    }
                    else
                    {
                        Console.WriteLine("下载PDF文件时发生错误,HTTP 状态码:" + response.StatusCode);
                    }
                }).Wait(); // 等待后台任务完成
            }
            catch (Exception ex)
            {
                Console.WriteLine("下载PDF文件时出错:" + ex.Message);
            }
        }
    }
}
举报

相关推荐

0 条评论