Client.DownloadString 问题
Client.DownloadString issue
代码应该读取原始的 Pastebin 获取它的 link 并下载它:
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: 'The Remote Server Returned An Error:
(302) Found.
有解决办法吗?
你查过the HTTP 302 code是什么意思吗?
The HyperText Transfer Protocol (HTTP) 302 Found redirect status response code indicates that the resource requested has been temporarily moved to the URL given by the Location
header. A browser redirects to this page...
响应包括 Location
header 指示您到资源所在的位置。您需要阅读 header 并遵循 URL.
因为这会抛出异常(我个人认为不应该,但根据你的描述看起来确实如此)那么你需要将其包装在a try/catch 来处理这个。从结构上看,这可能类似于:
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
代码应该读取原始的 Pastebin 获取它的 link 并下载它:
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: 'The Remote Server Returned An Error: (302) Found.
有解决办法吗?
你查过the HTTP 302 code是什么意思吗?
The HyperText Transfer Protocol (HTTP) 302 Found redirect status response code indicates that the resource requested has been temporarily moved to the URL given by the
Location
header. A browser redirects to this page...
响应包括 Location
header 指示您到资源所在的位置。您需要阅读 header 并遵循 URL.
因为这会抛出异常(我个人认为不应该,但根据你的描述看起来确实如此)那么你需要将其包装在a try/catch 来处理这个。从结构上看,这可能类似于:
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