本文介绍了即使 AllowAutoRedirect = true,HttpClient 也不会重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析 wikispaces 页面,但无法获取实际页面.我不确定它是 HttpClient 错误还是缺少一些配置.

I'm trying to parse a wikispaces page but I'm not able to get the actual page. I'm not sure if its a HttpClient bug or some missing configuration.

这是我的代码:

HttpClientHandler handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
_httpClient = new HttpClient(handler);

HttpResponseMessage response = await _httpClient
    .GetAsync("http://medivia.wikispaces.com/Monsters");

当我运行该代码时,我得到 StatusCode 302 并被发送到 https://session.wikispaces.com/1/auth/auth?authToken=token.我希望 HttpClient 遵循 302,因为我有 AllowAutoRedirect = true.

When i run that code I get the StatusCode 302 and get sent to https://session.wikispaces.com/1/auth/auth?authToken=token. I expect the HttpClient to follow a 302 because I have AllowAutoRedirect = true.

这是我第一次遇到这个问题.它适用于 Postman 和 RestClient,后者是 RestSharp 的一部分.

This is the first time I've encountered this problem. It works fine with Postman and RestClient which is part of RestSharp.

推荐答案

HttpClient 未正确重定向的原因是该站点将您重定向到 HTTPS,然后再返回到 HTTP.一个快速的解决方法是使用 https://medivia.wikispaces.com/Monsters 代替,这是一个更好的主意:

The reason the HttpClient isn't redirecting properly is because the site is redirecting you to HTTPS and then back to HTTP. A quick fix is to GET https://medivia.wikispaces.com/Monsters instead, which is a better idea anyhow:

HttpResponseMessage response = await _httpClient.GetAsync("https://medivia.wikispaces.com/Monsters");
// Works fine! :)

我很好奇为什么第一种方法不起作用,所以我挖得更深一些.如果您在浏览器或网络客户端中查看网络跟踪,则会发生以下情况:

I was curious why it didn't work the first way, so I dug a little deeper. If you watch the network trace in a browser or a network client, this is what happens:

GET http://medivia.wikispaces.com/Monsters
302 https://session.wikispaces.com/1/auth/auth?authToken=token
302 http://medivia.wikispaces.com/Monsters?redirectToken=token

从加密 (HTTPS) 连接到未加密连接的 302 导致 HttpClientHandler 自动停止跟随.据我所知,这是 HttpClientHandler 的 Windows 实现,因为 Unix one 在我的非正式测试中似乎并不关心 HTTPS->HTTP 重定向.

That 302 from an encrypted (HTTPS) connection to an unencrypted one is causing the HttpClientHandler to stop automatically following. From what I can tell, this is a security quirk of the Windows implementation of HttpClientHandler, because the Unix one didn't seem to care about the HTTPS->HTTP redirect in my informal testing.

这篇关于即使 AllowAutoRedirect = true,HttpClient 也不会重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 07:25