c# Webrequest Post 和 GetResponse

标签 c# webrequest iasyncresult webresponse

我正在编写一个程序,用于向网站提交 XML。编写的代码工作正常,但是有时它会因为某种原因停止工作,抛出一个 System.Net.ProtocolViolationException。我可以关闭程序并重新运行 - 它再次开始工作就好了。

这是我使用的代码:

private string Summit(string xml)
{
    string result = string.Empty;
    StringBuilder sb = new StringBuilder();
    try {
        WebRequest request = WebRequest.Create(this.targetUrl);
        request.Timeout = 800 * 1000;

        RequestState requestState = new RequestState(xml);
        requestState.Request = request;
        request.ContentType = "text/xml";

        // Set the 'Method' property  to 'POST' to post data to a Uri.
        requestState.Request.Method = "POST";
        requestState.Request.ContentType = "text/xml";

        // Start the Asynchronous 'BeginGetRequestStream' method call.    
        IAsyncResult r = (IAsyncResult)request.BeginGetRequestStream(new AsyncCallback(ReadCallBack), requestState);

        // Pause the current thread until the async operation completes.
        // Console.WriteLine("main thread waiting...");

        allDone.WaitOne();
        // Assign the response object of 'WebRequest' to a 'WebResponse' variable.
        WebResponse response = null;
        try {
            response =request.GetResponse();
        } catch (System.Net.ProtocolViolationException ex) {
            response = null;
            request.Abort();

            request = null;
            requestState = null;
            return "";
        }
        //Console.WriteLine("The string has been posted.");
        //Console.WriteLine("Please wait for the response...");

        Stream streamResponse = response.GetResponseStream();
        StreamReader streamRead = new StreamReader(streamResponse);
        Char[] readBuff = new Char[256];
        int count = streamRead.Read(readBuff, 0, 256);

        //StringBuilder sb = new StringBuilder();
        while (count > 0) {
            String outputData = new String(readBuff, 0, count);
            sb.Append(outputData);
            count = streamRead.Read(readBuff, 0, 256);
        }

        // Close the Stream Object.
        streamResponse.Close();
        streamRead.Close();
        //allDone.WaitOne();

        // Release the HttpWebResponse Resource.
        response.Close();
        //return sb.ToString();
    } catch (WebException webex) {
        Debug.WriteLine(webex.Message);

    } catch (System.Web.Services.Protocols.SoapException soapex) {
        Debug.WriteLine(soapex.Message);
    } catch (System.Net.ProtocolViolationException ex) {
        Debug.WriteLine(ex.Message);
    } catch (Exception ex) {
        Debug.WriteLine(ex.Message);
    }
    return sb.ToString();
}


private static void ReadCallBack(IAsyncResult asyncResult)
{
    try {
        RequestState myRequestState = (RequestState)asyncResult.AsyncState;
        WebRequest myWebRequest2 = myRequestState.Request;

        // End of the Asynchronus request.
        Stream responseStream = myWebRequest2.EndGetRequestStream(asyncResult);

        //Convert  the string into a byte array.
        ASCIIEncoding encoder = new ASCIIEncoding();
        byte[] ByteArray = encoder.GetBytes(myRequestState.Xml);

        // Write data to the stream.
        responseStream.Write(ByteArray, 0, myRequestState.Xml.Length);
        responseStream.Close();                  
    } catch (WebException e) {
        Console.WriteLine("\nReadCallBack Exception raised!");
        Console.WriteLine("\nMessage:{0}", e.Message);
        Console.WriteLine("\nStatus:{0}", e.Status);
    }
    allDone.Set();
}

response =request.GetResponse() 是失败报错的时候

You must provide a request body if you set ContentLength>0 or SendChunked==true. Do this by calling [Begin]GetRequestStream before [Begin]GetResponse.

如有任何帮助,我们将不胜感激。

最佳答案

这变得棘手,因为我们正在进行异步调用。

按以下顺序执行此操作:

request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request)

然后在'GetRequestStreamCallback(IAsyncResult asynchronousResult)'中调用:

request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request)

最后,在 GetResponse 中,确保关闭流:

response.Close();
allDone.Set();

MSDN 对其进行了很好的解释:http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx

关于c# Webrequest Post 和 GetResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18126941/

相关文章:

c# - 我收到错误 "There is no ViewData item of type ' IEnumerable<SelectListItem>'

c# - 参数 HTTP Post c#

c# - 从 Web 服务实例化对象与从常规类实例化对象

c# - 如何轻松地将两个异步请求链接在一起?

c# - 为什么嵌套字典的反序列化在 C# 中引发异常但在 F# 中有效?

c# - 在 c# 项目中定义了 'private accessors'

c# - 将多路径 SVG 转换为几何图形再转换为 WPF

时间:2019-03-17 标签:c#WebRequestcookies不工作

.net - 我可以使用委托(delegate)的单个实例来启动多个异步请求吗?

c# - 使用 1.events/2 使用 Web 服务的优缺点是什么。同步结果?