加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

.net – 如何在c#中读取httpWebRequest的请求流,我得到错误“流

发布时间:2020-12-15 06:42:57 所属栏目:百科 来源:网络整理
导读:我想从HttpWebRequest继承的自定义HttpWebRequest类中读取请求流,并尝试以不同的阶段读取请求流,但仍然不能确定如何在类中实现. 这个自定义的HttpWebRequest用于序列化一个soap消息,我想知道以字符串格式发送了什么请求.我还实现了自定义HttpRequestCreator,
我想从HttpWebRequest继承的自定义HttpWebRequest类中读取请求流,并尝试以不同的阶段读取请求流,但仍然不能确定如何在类中实现.

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

如果我在MemoryStream中输出所有内容,然后复制内容以请求流,任何人都知道我可以执行哪个阶段?在构造函数中,BeginGetRequestStream,EndGetRequestStream或GetRequestStream?

解决方法

如果出现错误返回码(如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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读