我有一个可以在浏览器中正常运行的ASP.NET MVC应用程序。
我正在使用以下代码来编写 检索到的页面的html到文件。 (这是用于PDF转换组件)
但是这段代码不断出错,但不会在浏览器中出错。
我有时会因为500错误而出现超时错误。
Public Function GetPage(ByVal url As String, ByVal filename As String) As Boolean
Dim request As HttpWebRequest
Dim username As String
Dim password As String
Dim docid As String
Dim poststring As String
Dim bytedata() As Byte
Dim requestStream As Stream
Try
username = "pdfuser"
password = "pdfuser"
docid = "docid=inv12154"
poststring = String.Format("username={0}&password={1}&{2}", username, password, docid)
bytedata = Encoding.UTF8.GetBytes(poststring)
request = WebRequest.Create(url)
request.Method = "Post"
request.ContentLength = bytedata.Length
request.ContentType = "application/x-www-form-urlencoded"
requestStream = request.GetRequestStream()
requestStream.Write(bytedata, 0, bytedata.Length)
requestStream.Close()
request.Timeout = 60000
Dim response As HttpWebResponse
Dim responseStream As Stream
Dim reader As StreamReader
Dim sb As New StringBuilder()
Dim line As String = String.Empty
response = request.GetResponse()
responseStream = response.GetResponseStream()
reader = New StreamReader(responseStream, System.Text.Encoding.ASCII)
line = reader.ReadLine()
While (Not line Is Nothing)
sb.Append(line)
line = reader.ReadLine()
End While
File.WriteAllText(filename, sb.ToString())
Catch ex As Exception
MsgBox(ex.Message)
End Try
Return True
End Function
答案 0 :(得分:0)
我建议您简化代码并处理一次性资源,例如流和流阅读器。您也可以使用WebClient:
Using client = New WebClient()
Dim values = New NameValueCollection()
values.Add("username", "pdfuser")
values.Add("password", "pdfuser")
values.Add("docid", "inv12154")
Dim result = client.UploadValues(url, values)
File.WriteAllBytes(filename, result)
End Using