簡體   English   中英

向服務器發送 http 請求而不期待響應

[英]Send http request to server without expecting a response

我需要向服務器發送 POST http 請求,但它不應該期待響應。 我應該使用什么方法?

我一直在使用

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

發送請求並返回響應。 如果請求將從服務器獲得響應,則此方法可以正常工作。 但是,為了我的需要,我只需要發送一個 POST 請求。 並且不會有與我發送的請求相關的響應。 我該怎么做?

如果我使用 request2.GetRespnse() 命令,我會收到“連接意外關閉”的錯誤消息

任何幫助將不勝感激。 謝謝

如果您使用的是 HTTP 協議,則必須有響應。

但是,它不需要是一個非常大的響應:

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

參考這個答案。

我認為您正在尋找的是 Fire and Forget 模式。

HTTP 需要響應,正如 Mike Caron 已經提到的。 但作為一個快速(骯臟的)修復,您可以捕獲“連接意外關閉”錯誤並繼續。

如果您的服務器對此沒問題,您始終可以使用 RAW 套接字發送請求然后關閉它。

看看這個可能會有所幫助。

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

}

如果您不想等待響應,您可以在另一個線程中發送數據或簡單地使用WebClient.UploadStringAsync ,但請注意響應總是在請求之后發生。 使用另一個線程進行請求允許您忽略響應處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM