執行下面一段代碼時,捕捉到異常:ProtocolViolationException
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "get"; byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes(data); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = requestBytes.Length; request.Timeout = 6000; try { Stream requestStream = request.GetRequestStream(); requestStream.Write(requestBytes, 0, requestBytes.Length); requestStream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default); ret = reader.ReadToEnd(); } catch (Exception) { return "Put data error"; }
原因是以流的方式提交數據的時候不能使用get方法,必須用post方法,改為下面的寫法即可。
request.Method = "post";