如何通过HTTP POST发送文件以及其他文本参数?

时间:2014-08-02 19:22:54

标签: asp.net vb.net csv post http-post

我目前正在设置我的方法,通过HTTP POST发送一些信息并获得响应。我将信息作为字符串发送到变量post_info中的函数。 (例如:"name=" & username & "&pass=" & password)。这有效,但我不知道如何像这样发送csv文件..." name = user& pass = password& file = [myfile]"。

Public Sub MyRequest(ByVal url As String, ByVal post_info As String, Optional SendingFile As Boolean = False)

    Dim req As HttpWebRequest
    Dim enc As UTF8Encoding
    Dim postdata As String
    Dim postdatabytes As Byte()

    req = HttpWebRequest.Create(url)
    enc = New System.Text.UTF8Encoding
    postdata = post_info
    postdatabytes = enc.GetBytes(postdata)
    req.Method = "POST"
    req.ContentType = "application/x-www-form-urlencoded"
    req.AllowWriteStreamBuffering = True
    req.ContentLength = postdatabytes.Length

    Using stream = req.GetRequestStream()
        stream.Write(postdatabytes, 0, postdatabytes.Length)
    End Using

    Using response As HttpWebResponse = req.GetResponse()
        Dim contentLength As Long = response.ContentLength
        Dim bytesReceived As Long = 0.0
        Dim bufferLength As Integer = 8192
        Dim buffer(bufferLength) As Char
        Dim sb As New StringBuilder

        Using reader As StreamReader = New StreamReader(response.GetResponseStream())
            Do
                Dim bufferedCount As Integer = reader.Read(buffer, 0, bufferLength)
                sb.Append(buffer, 0, bufferedCount)
                bytesReceived += bufferedCount
                Console.WriteLine(bytesReceived / contentLength * 100 & "%")
            Loop While bytesReceived < contentLength
        End Using

        json_response = JsonConvert.DeserializeObject(sb.ToString)

    End Using

End Sub

1 个答案:

答案 0 :(得分:0)

你有两个选择(第一个更容易,第二个更优雅):

  1. 在CSV文件内容上使用HttpUtility.UrlEncode,并在请求正文中使用此值:"name=user&pass=password&file=" + HttpUtility.UrlEncode(myfileContents)
  2. 使用专为此目的而设计的内容类型:multipart / form-data http://tools.ietf.org/html/rfc2388