当前位置: 首页 > 知识库问答 >
问题:

将多部分表单张贴到竹子API

堵浩波
2023-03-14

我在通过VB.NET控制台应用程序向BambooHR API提交多部分表单时遇到了很多困难。我已经发布了我当前的代码以及下面文档中的一个示例请求,当我运行这个代码时,我得到了(400)个坏请求。我知道代码很乱,但我一直在努力让它工作。

如有任何帮助,我们将不胜感激。

下面是我的代码:

Sub Main()

    upload(id, "https://api.bamboohr.com/api/gateway.php/company")

    Console.WriteLine()
    Console.WriteLine("Press ENTER to quit")
    Console.ReadLine()
End Sub

Function upload(ByVal employeeId As Integer, ByVal baseUrl As String)

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or SecurityProtocolType.Ssl3

    Dim boundary = "----BambooHR-MultiPart-Mime-Boundary----"
    Dim url = String.Format("{0}/v1/employees/{1}/files/", baseUrl, employeeId)

    Dim request As HttpWebRequest = WebRequest.Create(url)
    request.KeepAlive = True
    request.Method = "POST"
    request.ContentType = "multipart/form-data; boundary=" + boundary

    'Authorization is just the api key and a random string, in this case is x
    '
    Dim authInfo As String = api_key + ":" + "x"
    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo))
    request.Headers("Authorization") = "Basic " + authInfo


    Dim memStream As New MemoryStream()

    WriteMPF(memStream)

    request.ContentLength = memStream.Length

    Using requestStream = request.GetRequestStream()
        memStream.Position = 0
        Dim tempBuffer As Byte() = New Byte(memStream.Length - 1) {}
        memStream.Read(tempBuffer, 0, tempBuffer.Length)
        memStream.Close()
        requestStream.Write(tempBuffer, 0, tempBuffer.Length)
    End Using

    Dim webresponse As HttpWebResponse = request.GetResponse()
    Return webresponse

End Function

Private Sub WriteMPF(s As Stream)

    WriteToStream(s, "POST /api/gateway.php/company/v1/employees/id/files/ HTTP/1.0")
    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, "Host: api.bamboohr.com")
    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, "Content-Type: multipart/form-data; boundary=----BambooHR-MultiPart-Mime-Boundary----")
    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, "Content-Length: 520")
    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, vbCr & vbLf)

    WriteToStream(s, "------BambooHR-MultiPart-Mime-Boundary----")
    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, "Content-Disposition: form-data; name=""category""")
    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, "14")
    WriteToStream(s, vbCr & vbLf)

    WriteToStream(s, "------BambooHR-MultiPart-Mime-Boundary----")
    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, "Content-Disposition: form-data; name=""fileName""")
    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, "test.txt")
    WriteToStream(s, vbCr & vbLf)

    WriteToStream(s, "------BambooHR-MultiPart-Mime-Boundary----")
    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, "Content-Disposition: form-data; name=""share""")
    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, "no")
    WriteToStream(s, vbCr & vbLf)

    WriteToStream(s, "------BambooHR-MultiPart-Mime-Boundary----")
    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, "Content-Disposition: form-data; name=""file""; filename = ""test.txt""")
    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, "Content-Type: text/plain")
    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, "this is a test!")
    WriteToStream(s, vbCr & vbLf)

    WriteToStream(s, vbCr & vbLf)
    WriteToStream(s, "------BambooHR-MultiPart-Mime-Boundary------")
    WriteToStream(s, vbCr & vbLf)
End Sub

Private Sub WriteToStream(s As Stream, txt As String)
    Dim bytes As Byte() = Encoding.UTF8.GetBytes(txt)
    s.Write(bytes, 0, bytes.Length)
End Sub

下面是文档中的示例请求:(链接:https://www.bamboohr.com/api/documentation/employees.php向下滚动到“upload an Employee file”)

readme.txt------bamboohr-multipart-mime-boundary----content-disposition:表单-数据;name=“共享”

是------Bamboohr-Multipart-Mime-Boundary----Content-Disposition:Form-Data;name=“文件”;filename=“readme.txt”content-type:text/plain

这是一个示例文本文件。

------Bamboohr-Multipart-Mime-Boundary---

共有1个答案

牟子真
2023-03-14

在他们的GitHub上使用php示例并将其复制到VB.NET。有点乱,但很管用。下面是相关代码:

Public Function sendRequestMPF(ByVal req As BambooHTTPRequest, ByVal fileLocation As String) As BambooHTTPResponse
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or SecurityProtocolType.Ssl3

        Dim request As HttpWebRequest = WebRequest.Create(req.url)
        request.Method = req.method
        request.Host = "api.bamboohr.com"

        Dim boundary = "----BambooHR-MultiPart-Mime-Boundary----"

        Try
            request.ContentType = "multipart/form-data; boundary=" + boundary
            request.ContentLength = req.contents.Length
        Catch ex As Exception

        End Try

        Dim iCount As Integer = req.headers.Count
        Dim key As String
        Dim keyvalue As String

        Dim i As Integer
        For i = 0 To iCount - 1
            key = req.headers.Keys(i)
            keyvalue = req.headers(i)
            request.Headers.Add(key, keyvalue)
        Next

        Dim enc As System.Text.UTF8Encoding = New System.Text.UTF8Encoding()
        Dim bytes() As Byte = {}
        Dim pdfBytes() As Byte = {}
        Dim lBytes() As Byte = {}

        Dim fBytes() As Byte = {}
        Dim s As New MemoryStream()

        If (req.contents.Length > 0) Then
            bytes = enc.GetBytes(req.contents)
            s.Write(bytes, 0, bytes.Length)

            pdfBytes = File.ReadAllBytes(fileLocation)
            s.Write(pdfBytes, 0, pdfBytes.Length)

            Dim postHeader = vbCrLf + vbCrLf + "--" + boundary + "--" + vbCrLf
            Dim postHeaderBytes() As Byte = enc.GetBytes(postHeader)
            lBytes = enc.GetBytes(postHeader)
            s.Write(postHeaderBytes, 0, postHeaderBytes.Length)

            fBytes = s.ToArray()
            request.ContentLength = fBytes.Length
        End If

        request.AllowAutoRedirect = False

        If Not basicAuthUsername.Equals("") Then
            Dim authInfo As String = basicAuthUsername + ":" + basicAuthPassword
            authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo))
            request.Headers("Authorization") = "Basic " + authInfo
        End If

        If req.contents.Length > 0 Then
            Dim outBound As Stream = request.GetRequestStream()
            outBound.Write(fBytes, 0, fBytes.Length)
        End If

        Dim resp As BambooHTTPResponse
        Try
            Dim webresponse As HttpWebResponse = request.GetResponse()
            resp = New BambooHTTPResponse(webresponse)
            resp.responseCode = webresponse.StatusCode
            resp.headers = webresponse.Headers
        Catch e As WebException
            Console.WriteLine(e.Message)
            If (e.Status = WebExceptionStatus.ProtocolError) Then
                resp = New BambooHTTPResponse(DirectCast(e.Response, HttpWebResponse).StatusCode)
            Else
                resp = New BambooHTTPResponse(0)
            End If
        End Try

        Return resp
    End Function

Public Function buildMultiPart(ByVal params As NameValueCollection, ByVal boundary As String, ByVal contentType As String, ByVal name As String, ByVal fileName As String)
        Dim data = ""

        For Each key In params.AllKeys
            data += "--" + boundary + vbCrLf
            data += "Content-Disposition: form-data; name=""" + key + """"
            data += vbCrLf + vbCrLf
            data += params(key) + vbCrLf
        Next

        data += "--" + boundary + vbCr + vbLf
        data += "Content-Disposition: form-data; name=""" + name + """;" + " filename=""" + fileName + """" + vbCrLf
        data += "Content-Type: " + contentType + vbCrLf
        data += vbCrLf
        'data += fileData + vbCrLf + vbCrLf
        'data += "--" + boundary + "--" + vbCrLf

        Return data
    End Function

    Public Function uploadEmployeeFile(ByVal employeeId As Integer, ByVal fileName As String, ByVal fileLocation As String)
        Dim request As New BambooHTTPRequest()
        request.url = String.Format("{0}/v1/employees/{1}/files/", Me.baseUrl, employeeId)
        request.method = "POST"

        Dim boundary = "----BambooHR-MultiPart-Mime-Boundary----"

        Dim params = New NameValueCollection
        params.Add("category", "13")
        params.Add("fileName", fileName)
        params.Add("share", "no")

        request.contents = buildMultiPart(params, boundary, "application/pdf", "file", fileName)

        Return http.sendRequestMPF(request, fileLocation)
    End Function

所需的其余代码可以在他们的GitHub https://GitHub.com/bamboohr上找到

 类似资料:
  • 我试图在PHP中使用multipart/form-data头发布一个带有cURL的图像,因为我发送到的API期望图像以多部分形式发送。 我没有问题与API与其他请求;只有张贴图像是一个问题。 我在客户端使用此表单: 请求头中的content-type现在显示正确了。但是图像似乎没有像API所期望的那样正确地发送。不幸的是,我无法访问API... 感谢您的帮助,谢谢

  • 嗨,我有一个问题,当我可以尝试上载一个文件的属性和元数据到alFresco 5.2使用php 5.4.3,这是我的代码: $pam['body']是这样的: 这显示此错误: 但这个错误意味着一个或多个参数是错误的,但我不知道是哪个,因为服务器有大量的磁盘空间。 有什么帮助吗?有人使用ApiRest Alfresco 5.2和PHP吗?

  • 我想从React获取文件上传并将其发送到SpringBoot。我试图从React FormData发布,它将包含文件名和XML文件的键值对。因此,当我尝试将FormData发布到后端(即Springboot)时,它返回: 这是我的Springboot控制器: 我已经尝试在Axios post请求的头中指定multipart/form-data,但似乎不起作用。问题出在我的请求里还是出在我的控制器上

  • 我使用Django REST API和Angular 6作为前端。 我在配置文件模型中定义了一个接受文件输入的ImageField。 在angular应用程序中,我从Base64图像数据生成File对象,并发送到endpoint,标题为Content-type:'multipart/form-data' 编辑2:代码 方法正在使用方法发送数据。

  • 问题内容: 我们想将图像文件作为multipart / form发送到后端,我们尝试使用html表单获取文件并将文件作为formData发送,这是代码 后端中的错误是 “嵌套异常为org.springframework.web.multipart.MultipartException:无法解析多部分servlet请求;嵌套异常为java.io.IOException:org.apache.tomc

  • 我试图发送图像和文本字段到APIendpoint,但我收到 不支持的内容类型'多部分/表单数据;边界=---------------------------81801171514357 这是一个ASP. NET Core 2.1 Web API。我有这个: 而我的模特: 然后我使用axios: 我希望这个方法能够运行,而不是抛出异常。但是怎么做呢?我试图补充: 但是没有成功。 然后我试着: 该方法