简体   繁体   中英

HttpWebRequest POST method Exception

Currently I am using below method to post xml file content to extranet website. I am creating a new thread every 10 sec to post multiple files concurrently.

In this scenario I am getting this exception for many files : System.Net.WebException: The operation has timed out

Though it throws this exception still content of some exception files getting posted on the website.

1) Is it correct behavior that request getting posted even though there is time out exception for some files?

2) How to handle scenario like content for some exception file getting posted and not for other? How would I make sure which content not get posted so that I can try to re-post it?

3) Suggestions for other better implementation are welcome.

public void SendMessage(XmlDocument doc) {
    var httpWReq = (HttpWebRequest)WebRequest.Create(_extranetRemitService);

    httpWReq.Proxy = WebRequest.GetSystemWebProxy();
    httpWReq.Proxy.Credentials = CredentialCache.DefaultCredentials;
    httpWReq.UseDefaultCredentials = true;
    // encode xml file contents (melFileContents is a string)
    var melMessage = doc.InnerXml;
    byte[] data = Encoding.ASCII.GetBytes(melMessage);
    //post the xml data as text/xml content type
    httpWReq.Method = "POST";
    httpWReq.ContentType = "text/xml;charset=utf-8";
    httpWReq.ReadWriteTimeout = -1;
    httpWReq.KeepAlive = false;
    httpWReq.ContentLength = data.Length;
    using (Stream stream = httpWReq.GetRequestStream())
    {
        stream.Write(data, 0, data.Length);
    }
}

Thanks crackhaus and Jim Mischel. Below is the working example:

public void SendMessage(XmlDocument doc)
    {
        var httpWReq = (HttpWebRequest)WebRequest.Create(_extranetRemitService);
        httpWReq.Proxy = WebRequest.GetSystemWebProxy();
        httpWReq.Proxy.Credentials = CredentialCache.DefaultCredentials;
        httpWReq.UseDefaultCredentials = true;

        // encode xml file contents (melFileContents is a string)
        var melMessage = doc.InnerXml;
        byte[] data = Encoding.ASCII.GetBytes(melMessage);

        //post the xml data as text/xml content type
        httpWReq.Method = "POST";
        httpWReq.ContentType = "text/xml;charset=utf-8";
        httpWReq.ReadWriteTimeout = 10000;
        httpWReq.KeepAlive = false;
        httpWReq.ContentLength = data.Length;
        using (Stream stream = httpWReq.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
            stream.Close();
        }

        var response = (HttpWebResponse)httpWReq.GetResponse();
        response.Close();


    }

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