我试图找出这个" POST"请求,并将代码翻译成vb.net,用于webrequest。将评论我已经知道的内容
var xmlhttp; //Defining the "xmlhttp" variable
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest()
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
}
xmlhttp.onreadystatechange = function() { //If the xmlhttp is created then do this:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //Don't know
fired = true; //The function gathered the conditions to start
var title = '<div id="message_box_title_unavailable">woops!</div>'; //Doesn't matter
var result; //Variable "result"
if (xmlhttp.responseText == 'available') { //If the xml file contains "available" on it then do this, else return an error...
result = 'The name you selected <strong>' + user + 'is available!'
} else {
result = 'There was an error processing your request. Please try again.'
}
}
};
xmlhttp.open("POST", "Checkusername.php", true); //Didn't I translate this correctly?
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //What am I missing from this line in my vb code?
xmlhttp.send("name=" + name + "&n=" + Math.random()) //The same...
}
好的 - 我的Vb翻译
Dim req As HttpWebRequest
Dim res As HttpWebResponse
Dim cookies As New CookieContainer()
req = WebRequest.Create("http://blablabla.net/Checkusername.php?name=" & name "&n=" R.Next(0, 20000))
req.Method = "POST"
req.ContentType = "application/xml"
req.Headers.Add("Content-type", "application/x-www-form-urlencoded")
req.CookieContainer = cookies
res = req.GetResponse
Dim webStream As Stream
webStream = res.GetResponseStream
Dim reader As New StreamReader(webStream)
checksource.text = reader.readtoend
这总是给我一个&#34;错误&#34;而不是所需的结果,这在HTML
中始终是正确的基本上,我无法翻译第3/5行和最后的第3行。
感谢您的帮助!
答案 0 :(得分:0)
当您进行GET时,您在网址中提供参数。当您执行POST时,您在请求中提供它们。另外,如果您不使用cookie对象,也不确定为什么要创建cookie对象。
您不需要:
Dim res As HttpWebResponse
Dim cookies As New CookieContainer()
试试这个:
'Create the post string which contains the params
Dim postString As String = "name=" & name & "&n=" & R.Next(0, 20000)
'Create the request
req = WebRequest.Create("http://blablabla.net/Checkusername.php")
req.Method = "POST"
req.ContentLength = postString.Length
req.ContentType = "application/x-www-form-urlencoded"
'put the POST params in the request
Dim requestWriter As StreamWriter = New StreamWriter(req.GetRequestStream())
requestWriter.Write(postString)
requestWriter.Close()
'submit the request and read the response
Dim responseReader As StreamReader = New StreamReader(req.GetResponse().GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
'close everything
responseReader.Close()
req.GetResponse().Close()
responseData 将包含您的回复字符串
您还可以使用Try / Catch将其包围,以检查是否存在任何异常...网络连接不良,网址错误,无响应等.html中的xmlhttp.readyState == 4 && xmlhttp.status == 200
表示request finished
和{{ 1}}