我有一个程序,用户使用URL编码的查询字符串输入完整的URL,并将其发送到Web。
我在vb2005中使用httpwebrequest
我从网站上收到错误I should send a content length
如果网址为http://www.someurl.com/query.php?q=somtext¶m1=paramtext¶m2=paramtext2
如何从网址获取内容长度,因为无法自动知道这一点?
修改
我决定使用它,这是正确的
Private Function GetHtmlFromUrl(ByVal url As String, _
Optional ByVal PostData As String = vbNullString) As String
If url.ToString() = vbNullString Then
Throw New ArgumentNullException("url", "Parameter is null or empty")
End If
Dim html As String = vbNullString
Dim myUrl As New System.Uri(url)
Dim request As HttpWebRequest = WebRequest.Create(url)
With request
.ContentType = "Content-Type: application/x-www-form-urlencoded"
.Method = "POST"
.UserAgent = "Mozilla/4.0 (MSIE 6.0; Windows NT 5.1)"
.Referer = "http://www.google.com"
.ContentLength = myUrl.Query.Length
End With
Try
Dim response As HttpWebResponse = request.GetResponse()
Dim reader As StreamReader = New StreamReader(response.GetResponseStream())
html = Trim$(reader.ReadToEnd)
Return html
Catch ex As WebException
Return ex.Message
End Try
End Function
答案 0 :(得分:1)
问题在于您指定方法“POST”,但将参数作为URL传递是“GET”。您需要使用GET方法,或者需要执行POST(将参数写入请求流)。
http://www.codeproject.com/KB/webservices/HttpWebRequest_Response.aspx