在 Windows Phone 8.1 中,302 上的异常在 POST 后将 HTTPS 重定向到 HTTP

本文关键字:POST 异常 后将 HTTPS HTTP 重定向 Phone Windows | 更新日期: 2023-09-27 18:36:42

我正在尝试创建一个Windows Phone 8.1应用程序,该应用程序使用POST请求(使用Windows.Web.Http)登录到网站,然后继续访问另一个页面。当然,里面还有更多的代码,但我认为这与这个讨论无关。

HttpClient httpClient = new HttpClient();
...
HttpResponseMessage myHttpPostResponse = await httpClient.PostAsync(myUri,postContent);

我无法克服的挑战是在收到响应之前抛出异常。这是我在即时窗口中收到的消息:

A first chance exception of type 'System.Exception' occurred in mscorlib.ni.dll
System.Exception: Exception from HRESULT: 0x80072F08
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at App1.MainPage.<getSJWasync>d__1.MoveNext()

我的搜索使我相信这是由于Web服务器从https登录页面执行302重定向到不安全的http页面引起的...

在 MSDN 上找到...

"ERROR_INTERNET_HTTPS_TO_HTTP_ON_REDIR12040 (2F08)由于重定向,应用程序正在从 SSL 连接到非 SSL 连接。

使用我PC上的Chrome开发人员工具,我可以看到开机自检后确实存在302重定向。我试图通过不允许自动重定向(在 HttpBaseProtocolFilter 中)来手动处理重定向,但仍然抛出该异常。我尝试使用 try/catch 处理异常,但我不知道如何仍然获得 HttpResponseMessage。

在 Windows Phone 8.1 中,302 上的异常在 POST 后将 HTTPS 重定向到 HTTP

HttpBaseProtocolFilter中禁用自动重定向应该会阻止HttpClient引发异常。

下面是一个示例:

Uri uri = new Uri(
    "https://http2.cloudapp.net/?status=302&name=Location&value=http%3a%2f%2fkiewic.com");
HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
// Only needed to be able to connect to test server.
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
// Turn off auto-redirections.
filter.AllowAutoRedirect = false;
HttpClient client = new HttpClient(filter);
HttpStringContent content = new HttpStringContent("blah");
HttpResponseMessage response = await client.PostAsync(uri, content);
// Redirect URL is here.
Debug.WriteLine(response.Headers["Location"]);