发送HttpWebRequest登录网站

时间:2017-06-11 04:30:26

标签: c# android xamarin.android httpwebrequest

目前,我正在使用Xamarin在C#中构建(尝试)Android应用程序。

这是一个简单的应用程序登录到网站,从该网站检索一些数据并显示在屏幕上。

到目前为止,我只做了其他更简单的算法,而且我在发送“POST”请求时无法登录网站。

我从该网站获得的唯一信息是其上的html表单,我认为这是我需要的,但我不知道如何仅在此基础上创建HttpWebRequest:

<form name=form_login method=post action=valida.php role=form>
<fieldset>
<h1>QrCafé</h1>
<hr class=colorgraph>
<div class=form-group>
<input name=email type=email id=user_id class="form-control input-lg" 
placeholder=E-mail required>
</div>
<div class=form-group>
<input type=password name=senha id=password class="form-control input-lg" 
placeholder=Senha required>
</div>

我知道我必须执行POST以发送用户名和密码(我在变量中从用户处捕获,我只是不确定如何操作。任何帮助都将不胜感激。< / p>

2 个答案:

答案 0 :(得分:0)

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "hostUrl", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("fname=Henry&lname=Ford");
}
</script>

答案 1 :(得分:0)

  

我知道我必须执行POST来发送用户名和密码(我在变量中从用户处捕获,我只是不确定如何操作。

首先,我建议您使用Fiddler跟踪标题并发布您的请求所需的数据。

然后您可以在C#中执行发布请求,如下所示:

HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://mywebsite.com/valid.php");
req.Method = "POST";
//url encoding
string postData=WebUtility.UrlEncode("email=xiaxucheng@126.com&password=hudiai13");
byte[] byteArray = Encoding.UTF8.GetBytes(postData);

//conduct the request headers
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = byteArray.Length;

//conduct the post data
Stream dataStream = req.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

//get the response
WebResponse response = req.GetResponse();