我正在尝试从 url 下载文件。我尝试了两种方法,但它不适用于外部文件。
我认为它正在发生,因为我有代理互联网。我可以下载内部网络文件(图像、mp3、mp4 等等...),但是当我尝试在外部网络中下载某些内容时,它会给我timeout或404 Not Found。
第一种方法: System.Net.WebResponse、System.IO.FileStream
try
{
var credentials = new NetworkCredential("myNetworkUserName", "myNetworkPassword", "myNetworkDomain");
var proxy = WebProxy.GetDefaultProxy(); //new WebProxy("myNetworkProxy") <-- I TRY BOOTH WAYS
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://farm1.static.flickr.com/83/263570357_e1b9792c7a.jpg"); //External image link
proxy.Credentials = credentials;
request.Proxy = proxy;
responseExternalImage = request.GetResponse();//explode here ex=""Unable to connect to the remote server""
string fileName = GetFileName(response.ResponseUri.OriginalString);
Stream stream = response.GetResponseStream();
using (BinaryReader br = new BinaryReader(stream))
{
content = br.ReadBytes(50000000);//perto de 50Mb
br.Close();
}
response.Close();
FileStream fs = new FileStream(pathToSaveFile + "\\" + fileName, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
try
{
bw.Write(content);
}
finally
{
fs.Close();
bw.Close();
}
}
catch (Exception ex)
{
}
GetResponse()捕获的异常说:“无法连接到远程服务器”,“”连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立连接失败,因为连接的主机没有响应77.238.160.184:80""
第二种方法: System.Net.WebClient,DownloadFile
try
{
var credentials = new NetworkCredential("xpta264", ConfigurationManager.AppSettings["Xpta264Password"], "ptsi");
var proxy = WebProxy.GetDefaultProxy();
proxy.Credentials = credentials;
// Create a new WebClient instance.
using (WebClient myWebClient = new WebClient())
{
myWebClient.Proxy = proxy;
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile("http://farm1.static.flickr.com/83/263570357_e1b9792c7a.jpg", pathToSaveFile + "\\testImage.jpg");
}
}
catch (Exception e)
{
}
异常在DownloadFile方法中被捕获并给了我同样的错误。
希望可以有人帮帮我。
对不起我的英语不好