【发布时间】:2013-03-26 09:25:22
【问题描述】:
我正在尝试访问需要登录网站并传递参数列表的页面。我似乎能够登录该站点(如果我更改登录详细信息,我会收到 401 未经授权的错误),但随后会收到 400 错误请求错误。代码有点散列在一起,所以我知道出了点问题,但不知道在哪里。
编辑代码
Public Sub TestConn()
Dim customeremailaddress As String = HttpUtility.UrlEncode("r.test@test.com")
Dim customername As String = HttpUtility.UrlEncode("Ryan")
Dim referenceid As String = HttpUtility.UrlEncode("ordertest123")
Dim languagecode As String = HttpUtility.UrlEncode("1043")
Dim expirydays As String = HttpUtility.UrlEncode("30")
Dim UserName As String = "testusername"
Dim password As String = "testpassword"
Dim siteCredentials As New NetworkCredential(UserName, password)
Dim URLAuth As String = "http://service.someurl.com/process.xml"
Dim postString As String = String.Format("customeremailaddress={0}&customername={1}&referenceid={2}&languagecode={3}&expirydays={4}", customeremailaddress, customername, referenceid, languagecode, expirydays)
Dim postBytes As Byte() = Encoding.UTF8.GetBytes(postString)
Const contentType As String = "application/x-www-form-urlencoded"
System.Net.ServicePointManager.Expect100Continue = False
Dim cookies As New CookieContainer()
Dim webRequest__1 As HttpWebRequest = TryCast(WebRequest.Create(URLAuth), HttpWebRequest)
webRequest__1.Method = "POST"
webRequest__1.ContentType = contentType
webRequest__1.CookieContainer = cookies
webRequest__1.ContentLength = postBytes.Length
webRequest__1.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1"
webRequest__1.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
webRequest__1.Referer = "http://service.someurl.com/process.xml"
webRequest__1.Credentials = siteCredentials
Try
Dim requestStream As Stream = webRequest__1.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
Dim responseReader As New StreamReader(webRequest__1.GetResponse().GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
webRequest__1.GetResponse().Close()
Catch ex As Exception
Lbl_ConnTest_error.Text = ex.Message
End Try
End Sub
【问题讨论】:
-
首先使用 Fiddler2 fiddler2.com/fiddler2 查看请求/响应详细信息,看看是否指向正确的方向。
-
还可以查看这个示例msdn.microsoft.com/en-gb/library/debx8sh9.aspx - 它可能更容易阅读 - 而且它的 POSTing 数据不要忘记正确格式化 postData 即 url 编码值部分并创建键值对,即 variable1= Some%20value&variable2=Another%20Value
-
我认为这可能是我收到错误请求的地方,因为我不知道实际传递参数列表的语法是什么。我猜到了 - Dim postString As String = String.Format("customeremailaddress={0}&customername={1}&referenceid={2}&languagecode={3}&expirydays={4}", customeremailaddress, customername, referenceid, languagecode, expirydays ) - 但我确定这看起来不对?
-
您需要将 @Sani 的答案与围绕您的值包装 HttpServerUtility.UrlEncode() 结合起来,即 Dim customeremailaddress As String = HttpServerUtility.UrlEncode("r.test@test.com")
-
您现在正在写入字节两次。这就是内容长度不匹配的原因。您不需要
StreamWriter。删除与requestWriter对象有关的所有代码。正如 bUKaneer 所说,您还需要UrlEncode查询字符串中的值。
标签: asp.net vb.net web-services