[C#] 纯文本查看 复制代码 public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.StartPosition = FormStartPosition.CenterScreen;
}
public static CookieContainer mycookies;
private void btnlogin_Click(object sender, EventArgs e)
{
string userName = txtuser.Text.Trim();
string password = txtpassword.Text.Trim();
string html=login("http://192.168.1.1",userName,password);
textBox1.Text = html;
}
private void button2_Click(object sender, EventArgs e)
{
string html=get("http://192.168.1.1/userRpm/StatusRpm.htm?Disconnect=断 线&wan=1");
textBox1.Text = html;
}
public string login(string url,string userName,string password)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";
req.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:28.0) Gecko/20100101 Firefox/28.0";
req.KeepAlive = true;
req.Accept = "*/*";
req.PreAuthenticate = true;
CredentialCache myCache = new CredentialCache();
myCache.Add(new Uri(url), "Basic", new NetworkCredential(userName, password));//添加Basic认证
req.Credentials = myCache;
mycookies = new CookieContainer();
req.CookieContainer = mycookies;
HttpWebResponse resp;
try
{
resp= (HttpWebResponse)req.GetResponse();
resp.Cookies = mycookies.GetCookies(req.RequestUri);
StreamReader sr = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.Default);
String content = sr.ReadToEnd();
sr.Close();
resp.Close();
return content;
}
catch(WebException e)
{
resp = (HttpWebResponse)e.Response;
StreamReader sr = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.Default);
String content = sr.ReadToEnd();
sr.Close();
return content;
}
}
public string get(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UseDefaultCredentials = true;
request.ContentType = "text/html";
request.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:28.0) Gecko/20100101 Firefox/28.0";
request.Method = "get";
request.CookieContainer = mycookies;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(stream, Encoding.Default);
string content = responseReader.ReadToEnd();
stream.Close();
return content;
}
|