为什么我在尝试使用 HttpWebRequest 时收到 ProtocolViolationException?
-
21-09-2019 - |
题
我不知道。我正在尝试从我为 Windows Phone 构建的应用程序上的 REST 服务获取 XML。我总是在以下行中遇到异常:
HttpWebResponse response = request.EndGetResponse(ar) as HttpWebResponse;
我有以下设置(忽略错误的网址,这只是一个示例..)
HttpWebRequest request = WebRequest.Create("https://domain.chargify.com/customers.xml") as HttpWebRequest;
NetworkCredential credentials = new NetworkCredential("appkeyhere", "password");
request.Credentials = credentials;
request.Method = "GET";
request.ContentType = "text/xml";
request.BeginGetResponse(new AsyncCallback(SomeCallback), request);
...
private void SomeCallback(IAsyncResult ar) {
HttpWebRequest request = ar.AsyncState as HttpWebRequest;
HttpWebResponse response = request.EndGetResponse(ar) as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
XElement xmlResult = XElement.Parse(reader.ReadToEnd());
...
}
例外情况如下:
System.Net.ProtocolViolationException was unhandled
Message=ProtocolViolationException
StackTrace:
at System.Net.Browser.ClientHttpWebRequest.PrepareAndSendRequest(String method, Uri requestUri, Stream requestBodyStream, WebHeaderCollection headerCollection, CookieContainer cookieContainer)
at System.Net.Browser.ClientHttpWebRequest.BeginGetResponseImplementation()
at System.Net.Browser.ClientHttpWebRequest.InternalBeginGetResponse(AsyncCallback callback, Object state)
at System.Net.Browser.AsyncHelper.BeginOnUI(BeginMethod beginMethod, AsyncCallback callback, Object state)
at System.Net.Browser.ClientHttpWebRequest.BeginGetResponse(AsyncCallback callback, Object state)
at ChargifyWPA.MainPage.button1_Click(Object sender, RoutedEventArgs e)
at System.Windows.Controls.Primitives.ButtonBase.OnClick()
at System.Windows.Controls.Button.OnClick()
at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
at System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)
有人有主意吗?这是https,不是http..这是造成问题的原因吗?谢谢。
解决方案
我敢打赌,这个问题是因为你设置“ContentType的”头,但在你的要求不提供内容。注意尝试创建请求的协议则抛出异常。
您可能意味着设置“接受”标题为“text / xml”的,而不是内容类型头。
其他提示
这是不是你的问题,但它可能会帮助别人。我就遇到了这个,因为我是一个GET请求调用BeginGetRequestStream()。当然,这是没有必要的,我刚才一直在呼吁BeginGetResponse()。愚蠢的错误,但我早就想通了快了很多,如果错误信息已经更有帮助。
“内容类型”与“GET”报头将导致异常,如果存在请求 在天青表REST API它需要的ContentType编码成AUTH头虽然 - 使用空字符串GET的标头的“的ContentType”
显然,目前桌面上出现此错误的最常见原因是 Web 服务器需要 SSL 而不是 TLS 身份验证。查看所有评论 本文解释了各种 .NET 2 HTTP 错误的故障排除选项. 。看来您在 CodePlex 上获得 MIT 许可的 Chargify.NET 项目已经 使用此解决方法 (“安全协议类型.Ssl3”)。
其他可供尝试的选项 大约2008年的另一篇文章 正在回退到 HTTP/1.0 或禁用 Keep-Alive。
一定要尝试一下 这个答案, ,删除 ContentType 初始化。
不隶属于 StackOverflow