Send http request to server without expecting a re

2019-06-26 11:33发布

问题:

I have a need to send a POST http request to a server ,but it should not expect a response. What method should i use for it ?

I have been using

 WebRequest request2 = WebRequest.Create("http://local.ape-project.org:6969");
 request2.Method = "POST";
 String sendcmd = "[{\"cmd\":\"SEND\",\"chl\":3,\"params\":{\"msg\":\"Helloworld!\",\"pipe\":\"" + sub1 + "\"},\"sessid\":\"" + sub + "\"}]";
 byte[] byteArray2 = Encoding.UTF8.GetBytes(sendcmd);
 Stream dataStream2 = request2.GetRequestStream();
 dataStream2.Write(byteArray2, 0, byteArray2.Length);
 dataStream2.Close();
 WebResponse response2 = request2.GetResponse();

to send a request and get back a response. This works fine if the request will get a response back from the server. But, for my need, i just need to send a POST request. And there will be no response associated with the request i am sending. How do i do it ?

If i use the request2.GetRespnse() command , i get an error that "The connection was closed unexpectedly"

Any help will be appreciated. thanks

回答1:

If you're using the HTTP protocol, there has to be a response.

However, it doesn't need to be a very big response:

HTTP/1.1 200 OK
Date: insert date here
Content-Length: 0
\r\n


回答2:

refer to this answer.

What you are looking for, I think, is the Fire and Forget pattern.



回答3:

HTTP requires response as already mentioned by Mike Caron. But as a quick (dirty) fix you could catch the "connnection closed unexpectedly" error and continue.



回答4:

If your server is OK with this, you can always use RAW socket to send request then close it.



回答5:

If you don't want to wait for response you can send data in another thread or simple use WebClient.UploadStringAsync, but note that response always take place after request. Using another thread for request allows you to ignore response processing.



回答6:

Take a look at this it may help.

public static void SetRequest(string mXml)
{
    HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("http://dork.com/service");
    webRequest.Method = "POST";
    webRequest.Headers["SOURCE"] = "WinApp";

    // Decide your encoding here

    //webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.ContentType = "text/xml; charset=utf-8";

    // You should setContentLength
    byte[] content = System.Text.Encoding.UTF8.GetBytes(mXml);
    webRequest.ContentLength = content.Length;

    var reqStream = await webRequest.GetRequestStreamAsync();
    reqStream.Write(content, 0, content.Length);

    var res = await httpRequest(webRequest);

}