2016-09-18 1 views
1

HTTP 프로토콜에 대한 다운로드 방법이 있습니다. 그러나 그것이 제대로 작동하지 않는 것 같아, 뭔가 잘못되었습니다. 몇 가지 URL 소스로 테스트했는데 마지막 URL을 제외하고는 정확했습니다. ContentLength 속성이 URL에 잘못되었습니다. 런타임에는 210kb로 표시되지만 사실 8MB입니다. 내 코드를 공유하여 보여 드리겠습니다. 그것을 고치는 방법?ContentLength에 대해 HttpWebResponse가 잘못되었습니다.

코드 :

void TestMethod(string fileUrl) 
    { 
     HttpWebRequest req = WebRequest.Create(fileUrl) as HttpWebRequest; 
     HttpWebResponse resp = req.GetResponse() as HttpWebResponse; 
     long contentSize = resp.ContentLength; 

     MessageBox.Show(contentSize.ToString()); 
    } 
    private void TestButton_Click(object sender, EventArgs e) 
    { 
     string url1 = "http://www.calprog.com/Sounds/NealMorseDowney_audiosample.mp3"; 
     string url2 = "http://www.stephaniequinn.com/Music/Canon.mp3"; 

     TestMethod(url1); //This file size must be 8 MB, but it shows up as 210 kb. This is the problem 

     TestMethod(url2); //This file size is correct here, about 2.1 MB 
    } 

답변

1

난 당신이 (HttpWebRequest를 포함)이 방법이 URL에 액세스 할 수 없습니다 생각합니다.

는 응답 텍스트를 얻기 위해 시도하는 경우 :

<html><head><title>Request Rejected</title></head><body>The requested URL was rejected. If you think this is an error, please contact the webmaster. <br><br>Your support ID is: 2719994757208255263</body></html> 

당신은 전체 응답을 얻을 수 있도록 사용자 에이전트를 설정해야합니다

HttpWebRequest req = WebRequest.Create(fileUrl) as HttpWebRequest; 
    HttpWebResponse resp = req.GetResponse() as HttpWebResponse; 
    using (var streamreader = new StreamReader(resp.GetResponseStream())) 
    { 
     var r = streamreader.ReadToEnd(); 
     long contentSize = r.Length; 
     Console.WriteLine(contentSize.ToString()); 
    } 

당신이 응답을 얻을 것이다. 이와 같이 :

req.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0"; 

이 값을 설정하면 서버는 프로그램이 Firefox 브라우저라고 생각할 것입니다.

void TestMethod(string fileUrl) 
    { 
     HttpWebRequest req = WebRequest.Create(fileUrl) as HttpWebRequest; 
     req.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0"; 
     HttpWebResponse resp = req.GetResponse() as HttpWebResponse; 
     long contentSize = resp.ContentLength; 
     Console.WriteLine(contentSize.ToString()); 
    } 

좋은 하루 되세요 :

그래서 이러한 코드 몇 줄 트릭을 할해야합니다!

+0

잘 작동합니다. 'StreamReader'는 파일 다운로드를 기다리기 때문에 사용하지 않았습니다. 'UserAgent'를 설정하는 것이 더 낫고 올바른 크기를 반환 할 수 있습니다. 마지막으로,이 모질라'UserAgent'가 모든 HTTP 소스에서 작동합니까? 왜냐하면 나는 그것을 일반화해야하기 때문이다. @Quentin에게 감사합니다. –

+1

예이 사용자 에이전트는 모든 http 소스와 작동합니다. (URL에 표준 브라우저로 연결할 수있는 경우) –

+0

빠른 답장 보내 주셔서 감사합니다! 좋은 대답 –

관련 문제