2017-04-23 27 views
2

私は2つのURL:https://pcr.apple.com/id868222886https://jigsaw.w3.org/HTTP/300/302.htmlを持っています。両方ともロケーションリンクと302レスポンスコードを持っています。HttpClient 302リダイレクト

using System; 
using System.IO; 
using System.Net.Http; 

namespace XaveScor.PodcastFeed 
{ 
    public class RemoteFeedSource: FeedSource 
    { 
     private string url; 
     protected virtual HttpMessageHandler Handler => new HttpClientHandler() { AllowAutoRedirect = true }; 

     public override Stream Stream => client.Value.GetStreamAsync(url).Result; 

     private readonly Lazy<HttpClient> client; 

     public RemoteFeedSource(string url) 
     { 
      client = new Lazy<HttpClient>(() => new HttpClient(Handler), false);  
      this.url = url; 
     } 
    } 
} 


[TestMethod] 
public void Test1() //fail 
{ 
    var source = new RemoteFeedSource("https://pcr.apple.com/id868222886"); 
    Assert.AreNotEqual(source.Stream.GetString(), ""); 
} 

[TestMethod] 
public void Test2() //success 
{ 
    var source = new RemoteFeedSource("https://jigsaw.w3.org/HTTP/300/302.html"); 
    Assert.AreNotEqual(source.Stream.GetString(), ""); 
} 

なぜですか?違いは何ですか?あなたが応答でヘッダを見れば

+0

違いは、どのような意味ですか? 302 =見つかった(そしてリダイレクトによく使われる)、301 =永久に移動された。 [ここ](https://developer.att.com/application-resource-optimizer/docs/best-practices/http-300-status-codes)を参照してください。 – john

+0

@john私は2つの同一のリンクを持っています。しかし、このリンクではHttpClientの作業が異なります。私の質問はなぜですか?なぜ行動が違うのですか? – XaveScor

答えて

3

、あなたはこれを参照してくださいよ:

第1(https://pcr.apple.com/id868222886):

Content-Length: 0 
Location: http://beardycast.libsyn.com/rss 

2つ目(https://jigsaw.w3.org/HTTP/300/302.html):

Content-Length: 389 
Content-Type: text/html;charset=ISO-8859-1 
Location:  https://jigsaw.w3.org/HTTP/300/Overview.html 

したがって、最初のサーバーは自動的にリダイレクトされ、2番目のサーバーはいくつかの追加ヘッダーを提供します。

Strict-Transport-Security: max-age=15552015; includeSubDomains; preload 
Public-Key-Pins: pin-sha256="cN0QSpPIkuwpT6iP2YjEo1bEwGpH/yiUn6yhdy+HNto="; pin-sha256="WGJkyYjx1QMdMe0UqlyOKXtydPDVrk7sl2fV+nNm1r4="; pin-sha256="LrKdTxZLRTvyHM4/atX2nquX9BeHRZMCxg3cf4rhc2I="; max-age=864000 
X-Frame-Options: deny 
X-XSS-Protection: 1; mode=block 

とレスポンスボディ:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
       "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<title>Moved</title> 
</head> 
<body> 
<P>This resources has moved, click on the link if your browser doesn't support automatic redirection<BR> 
<A HREF="http://jigsaw.w3.org/HTTP/300/Overview.html">http://jigsaw.w3.org/HTTP/300/Overview.html</A></body> 
</html> 

HttpClientが非空の結果の文字列を返す理由はここにある - それは本当に空ではありません。あなたのユニットテストはステータスをチェックしていないので、設計方法が間違っていますが、レスポンスの長さだけをチェックしてください。3** HTTPステータスコードでも空ではない可能性があります。

関連する問題