簡體   English   中英

Xamarin Android httpwebrequest,無法訪問已處置的對象

[英]Xamarin Android httpwebrequest, Cannot access a disposed object

我有一個Android移動應用程序,我想發送webrequest到服務器發布一些數據,但在發布數據之前,我發送一個http獲取請求獲取一些數據,然后發送郵件請求,首先我收到成功,但當我在我的代碼requestStream.Write(bytes, 0, bytes.Length);這一行發送post請求它拋出波紋管異常requestStream.Write(bytes, 0, bytes.Length);

例外是:

System.ObjectDisposedException:無法訪問已處置的對象。 對象名:'System.Net.Sockets.NetworkStream'。

這是我的獲取和發布請求代碼GET:

public void GetTokenInfo()
        {

            try
            {
                var uri = new Uri(string.Format(_host + "webserver/SesTokInfo", string.Empty));
                var webRequest = WebRequest.Create(uri);
                using (var response = webRequest.GetResponse() as HttpWebResponse)
                {
                    using (var requestStream = response.GetResponseStream())
                    {
                        using (var reader = new StreamReader(requestStream))
                        {
                            var content = reader.ReadToEnd();
                            XmlDocument xDocument = new XmlDocument();
                            xDocument.LoadXml(content);
                            XmlElement root = xDocument.DocumentElement;
                            if (IsResponseReturned(root))
                            {
                                GlobalConfig.SessionId = root.GetElementsByTagName("SesInfo")[0].InnerText;
                                GlobalConfig.Token = root.GetElementsByTagName("TokInfo")[0].InnerText;

                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception);
            }
        }

使用此代碼我得到的結果沒有任何問題,這是我的POST:

 public WebResponse PostData(string body, string url)
        {
            WebResponse webResponse = null;
            try
            {
                var uri = new Uri(string.Format(_host + url, string.Empty));
                var webRequest = (HttpWebRequest)WebRequest.Create(uri);
                webRequest.Headers.Add("Cookie",
                    GlobalConfig.SessionId);
                webRequest.Headers.Add("_RequestVerificationToken", GlobalConfig.Token);
                webRequest.Method = "POST";
                webRequest.ContentType = "application/xml";
                byte[] bytes = Encoding.UTF8.GetBytes(body);
                webRequest.ContentLength = bytes.Length;
                Stream requestStream = webRequest.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                webResponse = webRequest.GetResponse();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
            return webResponse;
        }

我已經搜索並嘗試了方法,但我沒有得到解決方案,加上當我評論第一個函數,並且只運行第二個函數它將工作正常但是當我運行第一個然后第二個它拋出異常,做任何事情屬於從第一個代碼處置流和Web響應? 我認為使用聲明已經處理了它們。

任何幫助贊賞。

這可能只是確保使用正確的using語句,因為它們在適當時正確處理關閉傳出和傳入流。 請參閱以下修改示例,這應該適合您:

public string PostData(string body, string url)
{
    string responseText = null;

    try
    {
        var uri = new Uri(string.Format(_host + url, string.Empty));
        var webRequest = WebRequest.Create(uri) as HttpWebRequest;

        webRequest.Headers.Add("Cookie", GlobalConfig.SessionId);
        webRequest.Headers.Add("_RequestVerificationToken", GlobalConfig.Token);
        webRequest.Method = "POST";
        webRequest.ContentType = "application/xml";

        using (Stream requestStream = webRequest.GetRequestStream())
        {
            using (StreamWriter writer = new StreamWriter(requestStream))
            {
                writer.Write(body);
            }
        }

        var webResponse = webRequest.GetResponse() as HttpWebResponse;

        using (Stream responseStream = webResponse.GetResponseStream())
        {
            using (StreamReader reader = new StreamReader(responseStream))
            {
                responseText = reader.ReadToEnd();
            }
        }
    }
    catch (Exception exception)
    {
        Console.WriteLine(exception);
    }

    return responseText;
}

注意我已經將返回變量修改為字符串主體,這樣您就不會打開流。

幸田來未

  • 你的設備/模擬器是否連接到互聯網?

  • 您的應用程序是否需要連接到Internet的權限?

  • 您必須在調用webRequest.GetResponse()之前關閉請求流requestStream.Close() webRequest.GetResponse()

  • 需要像在GetTokenInfo()方法中那樣using IDisposable對象,否則你會遇到內存過度使用的問題

我只測試你的代碼和IT WORKS ,這是我的完整測試控制台應用程序

using System;
using System.IO;
using System.Net;
using System.Text;

namespace test01
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            PostData("a", "/");
        }

        public static WebResponse PostData(string body, string url)
        {
            WebResponse webResponse = null;
            try
            {
                var uri = new Uri(string.Format("http://google.it" + url, string.Empty));
                var webRequest = (HttpWebRequest)WebRequest.Create(uri);
                webRequest.Headers.Add("Cookie","test");
                webRequest.Headers.Add("_RequestVerificationToken", "test");
                webRequest.Method = "POST";
                webRequest.ContentType = "application/xml";
                byte[] bytes = Encoding.UTF8.GetBytes(body);
                webRequest.ContentLength = bytes.Length;
                Stream requestStream = webRequest.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                webResponse = webRequest.GetResponse();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
            return webResponse;
        }
    }
}

只是為了安全 - 嘗試刪除額外使用 - 而不是

using (var requestStream = response.GetResponseStream()) { using (var reader = new StreamReader(requestStream))

采用

using (var reader = new StreamReader(response.GetResponseStream())

有關詳細信息,請參閱https://msdn.microsoft.com/library/ms182334.aspx

在嘗試了很多方法並閱讀上面的答案並最終嘗試它們后,我通過使兩個代碼如下所示解決問題,獲得一個:

                var uri = new Uri(string.Format(_host + "webserver/SesTokInfo", string.Empty));
                var webRequest = WebRequest.Create(uri);
                using (var response = webRequest.GetResponse() as HttpWebResponse)
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        var content = reader.ReadToEnd();
                        XmlDocument xDocument = new XmlDocument();
                        xDocument.LoadXml(content);
                        XmlElement root = xDocument.DocumentElement;
                        if (IsResponseReturned(root))
                        {
                            GlobalConfig.SessionId = root.GetElementsByTagName("SesInfo")[0].InnerText;
                            GlobalConfig.Token = root.GetElementsByTagName("TokInfo")[0].InnerText;

                        }
                    }
                }

和POST一:

                var uri = new Uri(string.Format(_host + url, string.Empty));
                var webRequest2 = (HttpWebRequest)WebRequest.Create(uri);


                webRequest2.Headers.Add("Cookie",
                    GlobalConfig.SessionId);
                webRequest2.Headers.Add("_RequestVerificationToken", GlobalConfig.Token);
                webRequest2.Method = "POST";
                webRequest2.ContentType = "application/xml";

                byte[] bytes = Encoding.UTF8.GetBytes(body);
                webRequest2.ContentLength = bytes.Length;
                StreamWriter writer = new StreamWriter(webRequest2.GetRequestStream());
                writer.Write(bytes);
                webResponse = webRequest2.GetResponse();

當我在使用塊內部使用請求流時,它仍然會拋出異常,但是在使用塊時它會工作:)

暫無
暫無

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

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