C#发送http请求

发送http请求,可以用HttpWebRequest,比如:

HttpWebRequest logonReq = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:8097");

也可以直接发送基础字节,但要着重注意:

(1)发送和接收之间要有等待,否则收不到数据。

(2)注意\r\n的使用方式,不要有多余的空格。

 string logonReqStr = "";
            logonReqStr += "POST * HTTP/1.1\r\n";
            logonReqStr += "Content-Type:text/xml;charset=ISO-8859-1\r\n";
            logonReqStr += "Connection:Keep-Alive\r\n";
            logonReqStr += "SOAPAction:http://www.lucian.com/2001/04/ap#LogonRequest\r\n";
            logonReqStr += "Content-Length:263\r\n";
            logonReqStr += "\r\n";
            logonReqStr += "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Body><AP-MSG:LogonRequest xmlns:AP-MSG=\"http://www.lucin.com/2001/04/ap\" AP-MSG:UserName=\"\" AP-MSG:Password=\"\" ClientRequestHandle=\"3208\"/></SOAP-ENV:Body></SOAP-ENV:Envelope>";
            byte[] send = Encoding.UTF8.GetBytes(logonReqStr);
            Channel.Send(send, 0, send.Length);
            Thread.Sleep(1000);
            byte[] recvBuff=new byte[1024];
            int recvLen = Channel.ReceiveBySize(recvBuff,0, Channel.AvailableDataNum, 5000);
            string recv = Encoding.ASCII.GetString(recvBuff, 0, recvLen);string[] sArray = Regex.Split(recv, "\r\n", RegexOptions.IgnoreCase);