I am making a web request to login to an api. To authenticate the requested user, the api uses a string contained in the request. However, I cannot work out how to write this data to the request. I have used HTTP Live headers on firefox to find the request string and it gave me the following:
http://x/api/login
POST /api/login HTTP/1.1
Host: x
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0
Accept: */*
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://x/
Content-Length: 36
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
username=xxxxxx&password=xxxxxxx - HOW DO I SET THIS
I am wondering how to send a request with the bottom line included.
My current code is this:
apiReq.GetRequestStream().Write(Encoding.ASCII.GetBytes("username=" + username + "password=" + password), 0, Encoding.ASCII.GetBytes("username=" + username + "password=" + password).Length)
But it doesn't work...
Here's one way:
Dim webRequest = System.Net.HttpWebRequest.Create(YourURLHere)
webRequest.Method = "POST"
'If you are using credentials
webRequest.Credentials = New NetworkCredential("Username", "Password")
'Or if you just need to pass it in the request string
Dim postString as String = "username=Username&password=Password"
webRequest.ContentLength = postString.Length
webRequest.ContentType = "application/x-www-form-urlencoded"
Dim requestWriter As StreamWriter = New StreamWriter(webRequest.GetRequestStream())
requestWriter.Write(postString)
requestWriter.Close()
Dim responseReader As StreamReader = New StreamReader(webRequest.GetResponse().GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
webRequest.GetResponse().Close()
'responseData contains the response from the server