tags:

views:

136

answers:

1

I encountered the following exception: System.Net.ProtocolViolationException: You must write ContentLength bytes to the request stream before calling [Begin]GetResponse. at System.Net.HttpWebRequest.GetResponse() at Proxy.Form1.Form1_Load(Object sender, EventArgs e) in The following code works without proxy. I had tried asking around but to no avail. Can somebody shed a light?

Dim Str As String = String.Empty

Dim stream As Stream = Nothing

Dim policy As HttpRequestCachePolicy = New HttpRequestCachePolicy(HttpRequestCacheLevel.Default)

HttpWebRequest.DefaultCachePolicy = policy

Dim url As String = "http://www.jj919.com/post.asp"

Dim req As HttpWebRequest = DirectCast(WebRequest.Create(URL), HttpWebRequest)

Dim noCachePolicy As HttpRequestCachePolicy = New HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore)

req.CachePolicy = noCachePolicy

req.KeepAlive = True

req.AllowAutoRedirect = True

req.Timeout = 3000

req.ReadWriteTimeout = 3000

Dim p As New WebProxy()

Dim pUri As New Uri("http://202.75.43.20:808")

p.Address = pUri

p.Credentials = New NetworkCredential("test", "test")

req.Proxy = p

Dim postData As String = String.Format("name={0}", "sam")

Dim b As Byte() = System.Text.Encoding.UTF8.GetBytes(postData)

req.Method = "POST"

req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)"

req.ContentType = "application/x-www-form-urlencoded"

req.Headers.Add("Cache-Control", "no-cache")

req.Headers.Add("UA-CPU", "x86")

req.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US")

req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip")

req.Headers.Add(HttpRequestHeader.AcceptEncoding, "deflate")

req.ContentLength = b.Length

Try

req.GetRequestStream.Write(b, 0, b.Length)

Using res As HttpWebResponse = DirectCast(req.GetResponse(), HttpWebResponse)

Console.WriteLine("IsFromCache? {0}", res.IsFromCache)

If (Not res.Headers.Get("Content-Encoding") Is Nothing) Then

stream = New GZipStream(res.GetResponseStream, CompressionMode.Decompress)

Else

stream = res.GetResponseStream()

End If

Using sr As StreamReader = New System.IO.StreamReader(stream, Encoding.Default)

Console.WriteLine(sr.ReadToEnd)

End Using

End Using

Catch wex As Exception

Console.WriteLine(wex.ToString)

End Try

A: 

Hi, so whats wrong with my code or is it a bug with .net? I had asked around but no one had given me an ans, any help will be much appreciated. The POST url and proxy address is working for testing

Sam