5

C# dotnet 编写 curl 的用户名和密码逻辑

 3 years ago
source link: https://lindexi.gitee.io/post/C-dotnet-%E7%BC%96%E5%86%99-curl-%E7%9A%84%E7%94%A8%E6%88%B7%E5%90%8D%E5%92%8C%E5%AF%86%E7%A0%81%E9%80%BB%E8%BE%91.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
C# dotnet 编写 curl 的用户名和密码逻辑

在使用 curl 时,可以采用 -u 加上用户名和密码,这个对应在 C# 里面也是两句话的事情。只是在 curl 里面封装好了,我通过工具人协助解决,于是就在这里记录一下

假定使用 curl 输入的是如下代码

curl -ulindexi:FD7doYUzM7WApXobRb7X9qgURCF -T "E:\lindexi\doubi.exe" "https://blog.lindexi.com/artifactory/doubi.exe"

通过上面代码可以给我的存储服务上传文件,而如果使用 dotnet 编写,其实逻辑也十分简单

在账号密码这里,假定有变量 userName 和 key 分别是账号和密码,那么构建上传文件使用的账号密码将放在 Http 的 Header 里面,代码如下

            var encodedAuthString = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{userName}:{key}"));

            httpClient.DefaultRequestHeaders.Add("Authorization", $"Basic {encodedAuthString}");

而上传文件调用的是 Put 接口,整体逻辑如下

            var url = "https://blog.lindexi.com/artifactory/doubi.exeg";
            var file = @"E:\lindexi\doubi.exe";

            var userName = "lindexi";
            var key = "FD7doYUzM7WApXobRb7X9qgURCF";

            var encodedAuthString = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{userName}:{key}"));

            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("Authorization", $"Basic {encodedAuthString}");

            await httpClient.PutAsync(url, new StreamContent(File.OpenRead(file)));

看起来代码还是十分简单的,于是我就使用这个方法,在 GitHub 的 Action 上帮忙下载外网的内容,然后发送到我的国内服务器上

感谢工具人 lsj 提供的方法


本文会经常更新,请阅读原文: https://blog.lindexi.com/post/C-dotnet-%E7%BC%96%E5%86%99-curl-%E7%9A%84%E7%94%A8%E6%88%B7%E5%90%8D%E5%92%8C%E5%AF%86%E7%A0%81%E9%80%BB%E8%BE%91.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

如果你想持续阅读我的最新博客,请点击 RSS 订阅,推荐使用RSS Stalker订阅博客,或者前往 CSDN 关注我的主页

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接: https://blog.lindexi.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系

无盈利,不卖课,做纯粹的技术博客

以下是广告时间

推荐关注 Edi.Wang 的公众号
lindexi%2F201985113622445

欢迎进入 Eleven 老师组建的 .NET 社区
lindexi%2F20209121930471745.jpg

以上广告全是友情推广,无盈利


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK