2012-04-11 19 views
6

HttpWebRequestを使用していますが、GetResponse()を実行するとエラーが発生します。HttpWebRequestエラー:503サーバーを使用できません。

私はこのコードを使用:

private void button1_Click(object sender, EventArgs e) 
    { 
     Uri myUri = new Uri("http://www.google.com/sorry/?continue=http://www.google.com/search%3Fq%3Dyamaha"); 
     // Create a 'HttpWebRequest' object for the specified url. 
     HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri); 
     // Set the user agent as if we were a web browser 
     myHttpWebRequest.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4"; 

     HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); 
     var stream = myHttpWebResponse.GetResponseStream(); 
     var reader = new StreamReader(stream); 
     var html = reader.ReadToEnd(); 
     // Release resources of response object. 
     myHttpWebResponse.Close(); 

     textBox1.Text = html; 
    } 
+0

あなたは、同じエラーを取得しましたか? – jlafay

+1

これは、プログラムによって取得するためにはっきりと奇妙なURLのように見えます。それにはどんな理由がありますか? –

+1

http://www.google.com/sorry/は503を返します。Googleに多数のクエリを自動化しようとすると、そのURLを取得する可能性があります。しかし、Jon Skeet氏が尋ねたように、なぜそのURLにリクエストを提出しているのですか? http://support.google.com/websearch/bin/answer.py?hl=ja&answer=86640 –

答えて

11

サーバーが本当に503のHTTPステータスコードを返します。しかし、503のエラー条件(そのURLを開くとブラウザに表示される内容)とともにレスポンス本文も返されます。 プロパティでレスポンスにアクセスできます(応答が503件の場合は、WebExceptionの例外はResponseです)。あなたは具体的に、この例外をキャッチし、適切

をそれを処理する必要があり、あなたのコードは次のようになります。ブラウザやカールのようなツールでURLを要求するとき

string html; 

try 
{ 
    var myUri = new Uri("http://www.google.com/sorry/?continue=http://www.google.com/search%3Fq%3Dyamaha"); 
    // Create a 'HttpWebRequest' object for the specified url. 
    var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri); 
    // Set the user agent as if we were a web browser 
    myHttpWebRequest.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4"; 

    var myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); 
    var stream = myHttpWebResponse.GetResponseStream(); 
    var reader = new StreamReader(stream); 
    html = reader.ReadToEnd(); 
    // Release resources of response object. 
    myHttpWebResponse.Close(); 
} 
catch (WebException ex) 
{ 
    using(var sr = new StreamReader(ex.Response.GetResponseStream())) 
     html = sr.ReadToEnd(); 
} 

textBox1.Text = html; 
+0

このコードの仕事..ありがとうございます –

+1

@Ainun Nuha私はタイから英語に翻訳しようとしていますが、同様の問題に直面しています。 catch()ブロックでキャッチされているGetResponse()で例外が発生します。しかし、それはコンテンツ "Web Page Blocked"を含む完全なページのHTMLを送信します。文字列を英語に翻訳するにはどうすればいいですか? – RSB

関連する問題