VB.NET POST多个文件和参数

时间:2012-01-02 14:48:53

标签: vb.net post multipartform-data

我需要向服务器发出POST请求。 此请求必须具有多个参数,如下所示:

  • 名称
  • 宿主

和倍数文件

  • 文件1
  • file2的
  • file3的

我怎么能在VB.NET中做到这一点。我尝试了WebRequest对象,但没有简单的方法可以做到这一点。

感谢

2 个答案:

答案 0 :(得分:0)

我没有检查它是否有效,但我会尝试类似的事情:

' post request with some parameters inside query string
uriPath = String.Format("{0}{1}?func=xxx&uid={2}", url, fileName, id)
reqUri = New Uri(uriPath)
webReq = CType(WebRequest.Create(reqUri), HttpWebRequest)
webReq.Method = "Post"

' webReq.Timeout = 10000

webReq.KeepAlive = False
webReq.ContentType = "application/x-www-form-urlencoded"

' HERE is a place to attach your files
' try to run it at loop for each file
form = "name=" & fileName
webReq.ContentLength = form.Length
Dim sw As New StreamWriter(webReq.GetRequestStream, System.Text.Encoding.ASCII)
sw.Write(form)
' here write/send the file content
sw.Flush()
sw.Close()
sw.Dispose()

' reading response
Using res As WebResponse = webReq.GetResponse
    Dim st As Stream = res.GetResponseStream()
    Dim rd As New StreamReader(st)

    status = rd.ReadLine()

如果我记得发送了application/x-www-form-urlencoded类型的POST请求 以下列形式:

--- params separator
name=fileName
file content
--- params separator
name=fileName1
file1 content

答案 1 :(得分:0)

改为使用Webclient:

对于值:

' Create a value collection
Dim myNameValueCollection As New NameValueCollection()
' Set up POST variables
myNameValueCollection.Add("name", someName)
myNameValueCollection.Add("number", someNumber)
...
Using wc As New System.Net.WebClient()
    wc.UploadValues(remoteUrl, myNameValueCollection)
End Using

简单来说就是文件:

Using wc As New System.Net.WebClient()
    wc.UploadFile(remoteUrl, yourfile)
End Using