C#에서 Windows 응용 프로그램을 사용하여 HTTP 방법 수행
-
18-09-2019 - |
문제
양식 제출시 스크립트를 호출하여 HTTP 게시물을 사용하여 매개 변수로 전달하거나 전달하는 많은 사이트가 있습니다. 웹 디버거를 사용하여 매개 변수가 전달되는 것을 발견했습니다. 이제 C#의 Windows 응용 프로그램을 통해 같은 작업을 수행하고 싶습니다. 이러한 기능을 어떻게 달성 할 수 있습니까?
현재 C#에서 httpwebrequest 및 httpwebresponse 클래스를 사용하고 있습니다. 그러나로드하고 작업하려고하는 각 페이지에 대해 명시 적 코드를 작성해야하기 때문에 고통입니다. 예를 들어 사용자 이름과 비밀번호를 PHP 페이지로 전달하고 응답을 받으려고합니다.이 응답은 사용자가 로그인했는지 여부를 식별하는 쿠키와 페이지를 대가로 보냅니다.
HttpWebRequest loginreq = createreq("http://www.indyarocks.com/mobile/index.php");
String logintext = "username=" + TxtUsrname.Text + "&pass=" + TxtPasswd.Password + "&button.x=0&button.y=0";
loginreq.ContentLength = logintext.Length;
StreamWriter writerequest = new StreamWriter(loginreq.GetRequestStream());
writerequest.Write(logintext);
writerequest.Close();
HttpWebResponse getloginpageresponse = (HttpWebResponse)loginreq.GetResponse();
cookie = getloginpageresponse.Cookies[0];
BinaryFormatter bf1 = new BinaryFormatter();
Stream f1 = new FileStream("E:\\cookie.dat", FileMode.OpenOrCreate);
bf1.Serialize(f1, cookie);
f1.Close();
string nexturl = getloginpageresponse.Headers[HttpResponseHeader.Location];
StreamReader readresponse = new StreamReader(getloginpageresponse.GetResponseStream());
if (nexturl == "p_mprofile.php")
{
MessageBox.Show("Login Successful");
GrpMsg.IsEnabled = true;
}
else if (nexturl == "index.php?msg=1")
{
MessageBox.Show("Invalid Credentials Login again");
}
이것은 내 크레이어 레크 수업입니다
private HttpWebRequest createreq(string url)
{
HttpWebRequest temp = (HttpWebRequest)WebRequest.Create(url);
temp.Method = "POST";
temp.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506; .NET CLR 3.5.21022; FDM)";
temp.KeepAlive = true;
temp.ContentType = "application/x-www-form-urlencoded";
temp.CookieContainer = new CookieContainer();
temp.AllowAutoRedirect = false;
return temp;
}
내가 올바른 길을 가고 있습니까? 더 좋은 방법이 있습니까?
해결책
당신은 사용해야합니다 System.net.webclient.
원하는 메소드 및 헤더로 요청하여 간단한 스트림 읽기로 결과 페이지를 가져올 수 있습니다.
MSDN 페이지에는 간단한 예제가 있지만 사용하기위한 일부 샘플 코드는 다음과 같습니다.
WebClient webclient= new WebClient();
using (StreamReader reader = new StreamReader(webclient.OpenRead("http://www.google.com")))
{
string result = reader.ReadToEnd();
// Parse web page here
}
제휴하지 않습니다 StackOverflow