首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >了解WebRequest

了解WebRequest
EN

Stack Overflow用户
提问于 2010-12-29 11:23:08
回答 1查看 378关注 0票数 0

我找到了这段代码here,它允许您登录网站并从登录页面获取响应。然而,我在理解代码的所有部分时遇到了问题。到目前为止,我已经尽了最大努力填写我所理解的内容。希望你们能帮我填空。谢谢

代码语言:javascript
复制
string nick = "mrbean";
string password = "12345";

//this is the query data that is getting posted by the website. 
//the query parameters 'nick' and 'password' must match the
//name of the form you're trying to log into. you can find the input names 
//by using firebug and inspecting the text field
string postData = "nick=" + nick + "&password=" + password;

// this puts the postData in a byte Array with a specific encoding
//Why must the data be in a byte array?
byte[] data = Encoding.ASCII.GetBytes(postData);

// this basically creates the login page of the site you want to log into
WebRequest request = WebRequest.Create("http://www.mrbeanandme.com/login/");

// im guessing these parameters need to be set but i dont why?
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

// this opens a stream for writing the post variables. 
// im not sure what a stream class does. need to do some reading into this.
Stream stream = request.GetRequestStream();

// you write the postData to the website and then close the connection?
stream.Write(data, 0, data.Length);
stream.Close();

// this receives the response after the log in
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();

// i guess you need a stream reader to read a stream?
StreamReader sr = new StreamReader(stream);

// this outputs the code to console and terminates the program
Console.WriteLine(sr.ReadToEnd());
Console.ReadLine();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-12-29 11:28:02

流是一个字节序列。

为了在Stream中使用文本,您需要将其转换为字节序列。

这可以使用Encoding类手动完成,也可以使用StreamReaderStreamWriter自动完成。(将字符串读写到流中)

正如documentation for GetRequestStream中所述,

您必须调用Stream.Close方法来关闭流并释放连接以供重用。如果不能关闭流,则会导致应用程序耗尽连接。

方法和Content-*属性反映了底层的HTTP protocol

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4551247

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档