使用标头HttpWebRequest发送自定义字符串

时间:2014-07-25 17:35:08

标签: vb.net httpwebrequest

我正在发出登录api的网络请求。为了验证请求的用户,api使用请求中包含的字符串。但是,我无法弄清楚如何将此数据写入请求。我在firefox上使用了HTTP Live头来查找请求字符串,它给了我以下内容:

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

我想知道如何发送包含底线的请求。

我目前的代码是:

apiReq.GetRequestStream().Write(Encoding.ASCII.GetBytes("username=" + username + "password=" + password), 0, Encoding.ASCII.GetBytes("username=" + username + "password=" + password).Length)

但它不起作用......

1 个答案:

答案 0 :(得分:1)

这是一种方式:

        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