【问题标题】:how to read httpWebRequest's request stream in c#, i got error" the stream is not readable"?如何在 c# 中读取 httpWebRequest 的请求流,出现错误“流不可读”?
【发布时间】:2010-02-15 03:41:14
【问题描述】:

我想从继承自 HttpWebRequest 的自定义 HttpWebRequest 类中读取请求流,我尝试在不同阶段读取请求流,但仍不确定如何在类中实现。

这个自定义的HttpWebRequest是用来序列化一个soap消息的,我想知道以字符串格式发送了什么请求。我还实现了自定义HttpRequestCreatorHttpWebResponse,但仍然找不到可以读取请求流的位置/阶段。

如果我在MemoryStream 中输出所有内容,然后将内容复制到请求流,那么有人知道我可以在哪个阶段完成吗?在构造函数中,BeginGetRequestStreamEndGetRequestStreamGetRequestStream?

【问题讨论】:

  • 如果您想避免投票,请澄清您的问题。另外,如果你想得到一个好的答案。
  • 请发布您的代码,否则很难说出发生了什么。

标签: .net httpwebrequest


【解决方案1】:

如果有错误返回码,如 404、503、401 等,将导致“流不可读”。您可能没有检查您的状态码。

如果内容是文本,类似这样的工作:

public string DownloadString(string uri, out int status)
{
    string result= null;
    status = 0;
    HttpWebResponse response= null;
    try
    {
        HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(uri);
        // augment the request here: headers (Referer, User-Agent, etc)
        //     CookieContainer, Accept, etc.
        response= (HttpWebResponse) request.GetResponse();
        Encoding responseEncoding = Encoding.GetEncoding(response.CharacterSet);
        using (StreamReader sr = new StreamReader(response.GetResponseStream(), responseEncoding))
        {
            result = sr.ReadToEnd();
        }
        status = (int) response.StatusCode;
    }
    catch (WebException wexc1)
    {
        // any statusCode other than 200 gets caught here
        if(wexc1.Status == WebExceptionStatus.ProtocolError)
        {
            // can also get the decription: 
            //  ((HttpWebResponse)wexc1.Response).StatusDescription;
            status = (int) ((HttpWebResponse)wexc1.Response).StatusCode;
        }
    }
    finally
    {
        if (response!= null)
            response.Close();
    }
    return result;
}

【讨论】:

  • 问题是关于请求流,而不是响应流。
【解决方案2】:

你的问题不清楚。

如果您在其他代码写入流(POST 请求)之后尝试读取HttpWebRequest请求 流,这是不可能的。 (流直接发送到服务器,不存储在内存中)

相反,您需要公开自己的 MemoryStream,然后在准备好发送请求时将其写入 HttpWebRequest 的请求流。

【讨论】:

  • 非常感谢您的回复,您能告诉我哪个阶段/方法可以公开我的记忆流吗?再次感谢
【解决方案3】:

尝试使用Fiddler。为我工作。

提琴手:

  • 是一个Web调试代理
  • 记录您的计算机和 Internet 之间的所有 HTTP(S) 流量
  • 允许您检查所有 HTTP(S) 流量、设置断点和“摆弄”数据
  • 是免费软件
  • 可以调试来自几乎所有应用(网络浏览器等)的流量

【讨论】:

  • 这与此无关。这是 ASP 页面(或只是 c#)中对外部 URL 的请求,目的是在应用程序中使用原始请求中的数据。即使不是这样,我也不会在我的生产服务器上使用代理。
猜你喜欢
  • 2018-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-26
  • 1970-01-01
  • 2012-01-29
  • 1970-01-01
相关资源
最近更新 更多