HttpWebRequest.GetResponse()抛出WebException

时间:2012-02-28 18:50:01

标签: xamarin.android

我正在使用最新版本的Monodroid,4.04,并尝试使用HttpWebRequest连接到设备。我遇到的问题是GetResponse抛出一个webexception(见下文)。 在调试器中,当我设置断点时,我可以看到webRequest.HaveResponse == true,但异常中的响应为null。

为什么我在报告有回复时无法得到回复?

我正在使用的代码:

string responseFromServer;
        ServicePointManager.CertificatePolicy = new TestCertificatePolicy();

        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://192.168.1.1/login.cgi");
        webRequest.KeepAlive = true;
        webRequest.Method = "POST";
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.ContentLength = byteArray.Length;
        webRequest.ReadWriteTimeout = 10000;

        // Get the request stream.
        Stream dataStreamIn = webRequest.GetRequestStream();

        dataStreamIn.Write(byteArray, 0, byteArray.Length);
        dataStreamIn.Close();

        try
        {
            WebResponse response = webRequest.GetResponse(); <-- throws webexception
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);

            responseFromServer = reader.ReadToEnd();
            Console.WriteLine(responseFromServer);
            reader.Close();
            dataStream.Close();
            response.Close();

            Console.WriteLine("Done");

        }
        catch (WebException we)
        {
            Console.WriteLine(we);
            throw;
        }

以下是例外:

System.Net.WebException: Error getting response stream (ReadDone2): ReceiveFailure ---> System.Exception:    at System.Net.WebConnection.ReadDone(IAsyncResult result)
  at System.Net.WebConnection.HandleError (WebExceptionStatus st, System.Exception e, System.String where) [0x0003a] in /home/jon/Development/xamarin/mono/mcs/class/System/System.Net/WebConnection.cs:399 
  --- End of inner exception stack trace ---
  at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x0005e] in /home/jon/Development/xamarin/mono/mcs/class/System/System.Net/HttpWebRequest.cs:828 
  at System.Net.HttpWebRequest.GetResponse () [0x0000e] in /home/jon/Development/xamarin/mono/mcs/class/System/System.Net/HttpWebRequest.cs:836 
  at MonoDroidTest.Activity1.GetStreamPage (System.String url) [0x000c2] in C:\Users\dave\Documents\Visual Studio 2010\Projects\MonoDroidTest\MonoDroidTest\Activity1.cs:277

1 个答案:

答案 0 :(得分:0)

只是想说我最后通过套接字来解决这个问题。由于数据的性质,这可能是一种更好的方法。