gpt4 book ai didi

c# - HttpClient 302 重定向

转载 作者:行者123 更新时间:2023-11-30 21:41:18 36 4
gpt4 key购买 nike

我有 2 个网址:https://pcr.apple.com/id868222886https://jigsaw.w3.org/HTTP/300/302.html。两者都有位置链接和 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(), "");
}

为什么?有什么区别?

最佳答案

如果您查看响应中的 header ,您会看到:

第一个(https://pcr.apple.com/id868222886):

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

第二个(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

所以第一个服务器静静地重定向你,第二个服务器为你提供一些额外的 header :

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 状态代码,响应长度也可能是非空的。

关于c# - HttpClient 302 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43573321/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com