我想从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; }