简体   繁体   中英

Send http request to server without expecting a response

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

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

refer to this answer.

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

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.

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

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);

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM