我在.NET中寻找一个内置实用程序方法,用于为两种常见内容类型构建HTTP POST消息体:
我宁愿使用别人的准备和测试的实现,而不是使用自己的实现,即使我意识到这样做并不困难。但是System.Web
似乎没有任何结果。
有什么建议吗?
(无需解释如何手动构建POST消息体......这不是这个问题的内容)
答案 0 :(得分:2)
更简单,我喜欢WebClient.UploadValues方法。只需给它一个NameValueCollection,然后处理其余部分:
http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadvalues.aspx
答案 1 :(得分:0)
对于application/x-www-form-urlencoded
内容类型,只需使用UrlEncode
方法。
示例(在C#中):
string body =
"this=" + HttpUtility.UrlEncode(valueForThis) +
"&" +
"that=" + HttpUtility.UrlEncode(valueForThat) +
"&" +
"more=" + HttpUtility.UrlEncode(valueForMore);
答案 2 :(得分:-2)
Imports System.IO
Imports System.Net
Private Function PostWebPage(ByVal argUrl As String) As String
Dim objWebRequest As HttpWebRequest
Dim sPostData As New StringBuilder
Dim sr As StreamReader
Dim objWebResponse As HttpWebResponse
If argUrl.Length > 0 Then
Try
objWebRequest = CType(WebRequest.Create(argUrl), HttpWebRequest)
objWebRequest.UserAgent = "Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.1;+.NET+CLR+1.1.4322;+.NET+CLR+1.0.3705)"
sPostData.Append("accountType=GOOGLE&Email=*******@gmail.com&Passwd=*******&service=analytics&source=Test")
objWebRequest.Method = "POST"
objWebRequest.ContentType = "application/x-www-form-urlencoded"
objWebRequest.ContentLength = sPostData.ToString.Length
Dim stOut As New StreamWriter(objWebRequest.GetRequestStream, System.Text.Encoding.ASCII)
stOut.Write(sPostData)
stOut.Close()
objWebRequest.AllowAutoRedirect = True
objWebRequest.Timeout = 10000
objWebRequest.KeepAlive = True
objWebResponse = CType(objWebRequest.GetResponse(), HttpWebResponse)
sr = New StreamReader(objWebResponse.GetResponseStream)
Return sr.ReadToEnd
Exit Function
Catch ex As Exception
End Try
End If
Return ""
End Function