首页 > 编程语言 >212-c# url下载pdf,url请求,有参数,且携带cookies

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

时间:2023-11-12 18:02:16浏览次数:29  
标签:cookies 212 string using url System PDF var new

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

标签:cookies,212,string,using,url,System,PDF,var,new
From: https://blog.51cto.com/u_14816966/8330260

相关文章

  • 解决etcd服务--listen-metrics-urls=http://127.0.0.1:2381
     1、查看etcd的2381端口[root@master-nodemanifests]#netstat-anp|grep2381tcp00127.0.0.1:23810.0.0.0:*LISTEN21765/etcd2、获取etcd的pod[root@master-nodemanifests]#kubectlgetpod-ANAMESPACENAME......
  • 获取当前页面URL信息
    1,设置或获取对象指定的文件名或路径。window.location.pathname结果:/admin/index/index.html2,设置或获取整个URL为字符串。window.location.href结果:http://192.168.1.11/admin/index/news_edit.html?id=4,33,设置或获取与URL关联的端口号码。window.location......
  • Keepalived 提高吞吐量、负载均衡 ip_hash、负载均衡 url_hash 与 least_conn、Nginx
    Keepalived提高吞吐量keepalived:设置长连接处理的数量proxy_http_version:设置长连接http版本为1.1proxy_set_header:清除connectionheader信息upstreamtomcats{ #server192.168.1.173:8080max_fails=2fail_timeout=1s; server192.168.1.190:8080; #server......
  • url特殊字符传递参数解决方法(特指超链接)
    需要进行转码:十六进制值1.+URL中+号表示空格%2B2.空格URL中的空格可以用+号或者编码%203./分隔目录和子目录%2F4.?分隔实际的URL和参数%3F5.%指定特殊字符%256.#表示书签%237.&URL中指定的参数间的分隔符%268.=URL中指定参数的值%3D//带有特殊字......
  • Configuration failed because libcurl was not found. Try installing:
     01、问题R语言中安装"devtools"包报错如下:Configurationfailedbecauselibcurlwasnotfound.Tryinstalling: 02、解决方法:[root@pc1~]#yuminstalllibcurl-devel##根据提示安装 .  ......
  • ERROR: dependencies ‘openssl’, ‘curl’ are not available for package ‘creden
     001、问题:R语言安装“devtools” ERROR:dependencies‘openssl’,‘curl’arenotavailableforpackage‘credentials’ 002、解决方法: ......
  • urllib 2.x版本下dh key too small 等SSL类错误的解决方法
    问题当我们使用python的requests访问目标网站的时候,有时会遇到以下这种错误(以https://dh-composite.badssl.com/为例)requests.exceptions.SSLError:HTTPSConnectionPool(host='dh-composite.badssl.com',port=443):Maxretriesexceededwithurl:/(CausedbySSLError......
  • 企业微信开启接收消息+验证URL有效性
    企业微信开启接收消息+验证URL有效性......
  • js判断url是否可用
    问题需要判断url是否可用,再去执行其他操作,代码如下:constloadScript=(url)=>{returnnewPromise((resolve,reject)=>{constscript=document.createElement('script')script.onload=()=>resolve(true)script.onerror=()=>resolve(fa......
  • Java根据URL截图的4种方式
    方案选择XHTMLRenderer(不要用)PhantomJs(三方库,已停更)Puppeteer(Chrome团队开发和维护)Selenium(支持多浏览器、多语言,服务器需要安谷歌浏览器)一、XHTMLRenderer(不要用)XHTMLRenderer它是一个Java库,用于将XHTML文档渲染为图像或PDF格式。也不要用它来转PDF1、XHTMLRenderer......