Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting ProtocolViolationException when trying to use HttpWebRequest?

I've no idea. I'm trying to get XML from a REST service on an app I'm building for Windows Phone. I always get an exception at the following line:

HttpWebResponse response = request.EndGetResponse(ar) as HttpWebResponse;

I have the following setup (ignore the bad url, it's just an example .. )

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());
    ...
}

The exception is as follows:

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)

Anyone have any ideas? It is https, not http .. is that causing the issue? Thanks.

like image 659
djbyter Avatar asked Mar 19 '10 20:03

djbyter


1 Answers

This isn't your problem, but it might help somebody else. I ran into this because I was calling BeginGetRequestStream() on a GET request. Of course, that's not necessary and I should have just been calling BeginGetResponse(). Silly mistake, but I would have figured it out a lot faster if the error message had been more helpful.

like image 60
mhenry1384 Avatar answered Oct 04 '22 00:10

mhenry1384