简体   繁体   English

HttpWebResponse.GetResponseStream()。Length引发异常,即使结果为200 OK状态

[英]HttpWebResponse.GetResponseStream().Length throws exception even result is 200 OK status

I am trying to connect the web url from ASP.Net application to java web application using HttpWebRequest object and getting the status 200 OK. 我试图使用HttpWebRequest对象将ASP.Net应用程序中的Web URL连接到Java Web应用程序,并获得状态200 OK。 But when i try reading the response content using GetResponseStream() i am getting an error 'responseStream.Length' threw an exception of type 'System.NotSupportedException' 但是,当我尝试使用GetResponseStream()读取响应内容时,出现错误“ responseStream.Length”,引发了类型为“ System.NotSupportedException”的异常

Here is the code 这是代码

string uri="https://myapp.com/mainservlet/";

System.Net.HttpWebRequest hwrequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
            hwrequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            hwrequest.AllowAutoRedirect = true;
            hwrequest.UserAgent = "http_requester/0.1";
            hwrequest.Timeout = 60000;
            hwrequest.Method = "POST";
            if (hwrequest.Method == "POST")
            {
                hwrequest.ContentType = "text/xml";
                // Use UTF8Encoding instead of ASCIIEncoding for XML requests:
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                byte[] postByteArray = encoding.GetBytes(postData);
                hwrequest.ContentLength = postByteArray.Length;
                 System.IO.Stream  poststream = hwrequest.GetRequestStream();
                poststream.Write(postByteArray, 0, postByteArray.Length);
                poststream.Close();
            }

            //Get the Response now.
            hwresponse = (System.Net.HttpWebResponse)hwrequest.GetResponse();

         //  System.Xml.Linq.XDocument doc;
            //hwresponse.Method = "GET";
            string str = hwresponse.CharacterSet;
            string str1 = hwresponse.ContentEncoding;
            if (hwresponse.StatusCode == System.Net.HttpStatusCode.OK)
            {

                System.IO.Stream responseStream = hwresponse.GetResponseStream();
               // Here i am getting that exception

Note: When i try paste the same url in browser it says 注意:当我尝试在浏览器中粘贴相同的网址时,它说

Error 404--Not Found From RFC 2068 Hypertext Transfer Protocol -- HTTP/1.1: 10.4.5 404 Not Found The server has not found anything matching the Request-URI. 错误404-从RFC 2068超文本传输​​协议中找不到-HTTP / 1.1:10.4.5 404未找到服务器找不到与请求URI匹配的任何内容。 No indication is given of whether the condition is temporary or permanent. 没有迹象表明这种情况是暂时的还是永久的。 If the server does not wish to make this information available to the client, the status code 403 (Forbidden) can be used instead. 如果服务器不希望将此信息提供给客户端,则可以改用状态代码403(禁止)。 The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. 如果服务器通过某种内部可配置的机制得知旧资源永久不可用并且没有转发地址,则应使用410(已消失)状态代码。

Also it entered in 200 OK status and shows exception. 它还进入200 OK状态并显示异常。 Could some one help me how to resolve/ suggession? 有人可以帮我解决/建议吗?

Use this to get the response have been using it for 4 years now always works. 用它来获取已经使用了4年的响应,现在可以正常使用。

 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream responseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(responseStream);
                responseData = myStreamReader.ReadToEnd();
            }
            response.Close();

Why are you checking if it is a post? 为什么要检查它是否是帖子?

Try reading the stream like this instead. 尝试像这样读取流。 Then you can also set how much data of the webpage that you actually want. 然后,您还可以设置所需的网页数据量。

Dim ResponseStream As Stream = Response.GetResponseStream()
            Try
                Dim reader As New StreamReader(Stream.Null)
                Try
                    reader = New StreamReader(ResponseStream, System.Text.Encoding.GetEncoding(CharSet), True, 256)
                Catch ex As Exception

                    '
                    ' Redo the stream
                    '
                    If InStr(ex.Message, "not a supported encoding name.") > 0 Then
                        Try
                            reader = New StreamReader(ResponseStream, System.Text.Encoding.GetEncoding("utf-8"), True, 256)
                        Catch ex1 As Exception

                        End Try
                    End If
                End Try
                '
                'Dim string to build index.
                '
                Dim IndexBuildString As New StringBuilder()
                Try
                    Dim read(256) As [Char]
                    '
                    ' Reads 256 characters at a time.    
                    '
                    Dim ByteCount As Integer = reader.Read(read, 0, 256)
                    '
                    ' Read in while, exit it if exceeds ~ 390 kb
                    '
                    While ByteCount > 0
                        '
                        'Check if limit of kilobytes are over the limit.
                        '
                        If System.Text.ASCIIEncoding.Unicode.GetByteCount(IndexBuildString.ToString()) > 153600 Then
                            Exit While
                        End If
                        '
                        'Dumps the 256 characters to a string and displays the string to the console.
                        '
                        Dim str As New [String](read, 0, ByteCount)
                        ByteCount = reader.Read(read, 0, 256)
                        '
                        'Append to the StringBuilder
                        '
                        IndexBuildString.Append(str)
                    End While
                    '
                    'Assign the Stringbuilder and then clear it
                    ' 
                    IndexString = CleanIndexString(IndexBuildString.ToString())
                Catch ex As Exception

                Finally

                    Try
                        IndexBuildString.Clear()
                        reader.Close()
                        reader.Dispose()
                    Catch ex As Exception

                    End Try
                End Try
            Catch ex As Exception

            Finally
                ResponseStream.Dispose()
            End Try

You must add your own error handling.... 您必须添加自己的错误处理...。

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

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