首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Client.DownloadString问题

Client.DownloadString问题
EN

Stack Overflow用户
提问于 2021-08-14 16:57:18
回答 1查看 67关注 0票数 0

代码应该读取原始Pastebin,获取其链接并下载:

代码语言:javascript
复制
        WebClient webClient = new WebClient();
        var client = new WebClient();
        string SourceDir = @"./";
        string SourceZip = @"./FILE";
        string Download = client.DownloadString("PastebinLink");
        client.DownloadFile(Download, @"File");
        ZipFile.ExtractToDirectory(SourceZip, SourceDir);
        System.IO.File.Delete(SourceZip);
        Process.Start(@"./FILE");

当我调试它时,它的反应是

System.Net.WebException:“远程服务器返回了一个错误:(302)找到了。

有解决办法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-14 17:09:31

你查过HTTP 302代码的意思了吗?

HyperText传输协议(HTTP302) 302找到重定向状态响应代码,表示请求的资源已临时移动到由Location报头提供的URL。浏览器重定向到此页面..。

响应包括指向资源所在位置的Location头。您将需要读取该标题并遵循该URL。

因为这会抛出一个异常(我个人认为不应该,但根据您的描述,它看起来应该异常),所以您需要将它包装在一个try/catch中来处理。从结构上看,这可能类似于:

代码语言:javascript
复制
string Download = "";
try
{
    Download = client.DownloadString("PastebinLink");
}
catch (WebException ex)
{
    // See if the response contains a Location header
    string newLink = ex.Response?.Headers.Get("Location");
    if (!string.IsNullOrEmpty(newLink))
    {
        // If the response contained a Location header, use it
        Download = client.DownloadString(newLink);
    }
    else
    {
        // The error response didn't contain a Location header
        // so let the exception continue up the stack
        throw;
    }
}

if (Download == "")
{
    // The attempt failed, handle the problem here
}

// The attempt succeeded, continue with your logic here
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68785374

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档