Send http request to server without expecting a re

2019-06-26 11:29发布

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

6条回答
戒情不戒烟
2楼-- · 2019-06-26 11:49

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.

查看更多
别忘想泡老子
3楼-- · 2019-06-26 11:57

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
查看更多
【Aperson】
4楼-- · 2019-06-26 12:07

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

查看更多
够拽才男人
5楼-- · 2019-06-26 12:12

refer to this answer.

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

查看更多
家丑人穷心不美
6楼-- · 2019-06-26 12:12

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.

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-06-26 12:12

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

}

查看更多
登录 后发表回答