Using WebRequest and WebClient, two ways to request an application published by the HTTP service, the result is an exception.
There are three kinds, 1, System.Net.WebException: The server submitted a protocol conflict. Section=responsestatusline
2, System.Net.WebException: The underlying connection has been closed: The connection was closed unexpectedly.
3. System.Net.ProtocolViolationException: Unable to send content body with this predicate type.
In addition, the same code, the request for normal page no problem, return to normal.
Analysis:
1, the requested application, although the application of the HTTP service, but did not fully comply with the HTTP protocol. Cause, some parameter mates are required for the request.
2, WebRequest and WebClient, configurable parameters are few, may not meet the requirements.
3, in fact, the HTTP service is a special case of the TCP protocol, all the methods to solve the TCP problem can be used on HTTP
Solve:
1, first think of the socket application, because it is the most basic method of solving TCP. However, due to the header of the HTTP request, there was no too deep research and the result failed.
2, think of the original used TcpClient, more convenient than the socket to use. The problem is solved.
Source:
Private stringGETHTMLTCP (stringURL) { stringstrHTML ="";//used to save the obtained HTML codeTcpClient Clientsocket =NewTcpClient (); Uri URI=NewUri (URL); Clientsocket.connect (URI. Host, URI. Port); StringBuilder requestheaders=NewStringBuilder ();//used to save HTML protocol header informationRequestheaders.appendformat ("{0} {1} http/1.1\r\n","GET", URI. Pathandquery); Requestheaders.appendformat ("connection:close\r\n"); Requestheaders.appendformat ("host:{0}\r\n", URI. Host); Requestheaders.appendformat ("accept:*/*\r\n"); Requestheaders.appendformat ("accept-language:zh-cn\r\n"); Requestheaders.appendformat ("user-agent:mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1;. NET CLR 1.1.4322;. NET CLR 2.0.50727) \r\n\r\n"); Encoding Encoding=Encoding.default; byte[] Request =encoding. GetBytes (Requestheaders.tostring ()); ClientSocket.Client.Send (Request); //get the network stream to saveStream Readstream =Clientsocket.getstream (); StreamReader SR=NewStreamReader (Readstream, Encoding.default); strHTML=Sr. ReadToEnd (); Readstream.close (); Clientsocket.close (); returnstrhtml; }
C # Problems when requesting remote HTTP services through WebRequest