繁体   English   中英

c#Webrequest Post和GetResponse

[英]c# Webrequest Post and GetResponse

我正在编写一个程序,它将向网站提交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()是失败并发出错误

如果设置ContentLength> 0或SendChunked == true,则必须提供请求正文。 通过在[Begin] GetResponse之前调用[Begin] GetRequestStream来完成此操作。

任何帮助将不胜感激。

由于我们正在进行异步调用,因此这很棘手。

按以下顺序执行此操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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