Вложения с использованием веб-сервиса REST и VB.NET

#vb.net #rest #attachment #rt

#vb.net #rest #вложение #rt

Вопрос:

В настоящее время я разрабатываю приложение с использованием VB.NET в котором я использую веб-сервисы REST. Я смог выполнить основы с помощью REST, однако мне не удалось добавить вложение (более конкретно, загрузить файл, используя REST, который прикрепляется). Я провел обширное исследование в Интернете, но пока мне не удалось найти ни одного рабочего примера в VB.NET . Для фактической загрузки данных я использую System.Net.WebClient. Следующее VB.NET код выполняет важную работу:

 Dim Client As New System.Net.WebClient
Dim postBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(postString)
Client.UploadData(URL, "POST", postBytes)
  

Упрощенная версия моего URL выглядит следующим образом:
"../REST/1.0/ticket/" ticketNumber "/comment?user=" userName "amp;pass=" password

Наконец, примером контента, который я публикую, является:

 postString = "content=Text: RT Test"   vbLf   "Action: Comment"   vbLf   "Attachment: examplefile.jpg"   vbLf   "attachment_1="
  

Как вы можете видеть, postString преобразуется в байты и затем загружается на сервер. Однако я не знаю, где и как я должен размещать само необработанное вложение. В документации к сервису, который мы специально используем, указано, что используется переменная «attachment_1», которую я добавил к переменной postString, но я не уверен, каким должен быть следующий шаг. Следует ли преобразовать файл в байты и добавить к переменной postBytes? Я попытался сделать что-то подобное, но я получил сообщение об ошибке, в котором говорится, что вложение не найдено для examplefile.jpg .

Спасибо за вашу помощь!

Комментарии:

1. Вы пробовали кодировать данные в Base64? Convert.ToBase64String(bytes)

2. Спасибо за предложение. Однако, похоже, у меня не сработало, как вы на самом деле добавляете вложение? МЫ проходим через интерфейс REST, поэтому в конце URL-адреса мы переходим: «URL content =… Вложение: filename.xtension Действие: комментарий …. attachment_1=» Преобразовать. ToBase64String(файловые байты (the file)) Где FileAsBytes() — это функция, которая преобразует файл вложения в байты, однако ответ возвращается как: «… Неверный запрос …», Не могу вспомнить точную формулировку частей, поскольку сейчас не работаю, какие-либо предложения или более точные детали? Спасибо.

Ответ №1:

Мы не смогли использовать Client.UploadData(…) и должен был преобразовать весь post в байты, начиная с полей POST перед вложением, затем само вложение и, наконец, остальные поля POST.

 Public Sub AddAttachmentToRT(ByVal url As String, ByVal fileName As String, ByVal filePath As String)

    Dim dataBoundary As String = "--xYzZY"
    Dim request As HttpWebRequest
    Dim fileType As String = "image/jpeg" 'Will want to extract this to make it more generic from the uploaded file.

    'Create a POST web request to the REST interface using the passed URL
    request = CType(WebRequest.Create(url), HttpWebRequest)
    request.ContentType = "multipart/form-data; boundary=xYzZY"
    request.Method = "POST"
    request.KeepAlive = True

    'Write the request to the requestStream
    Using requestStream As IO.Stream = request.GetRequestStream()

        'Create a variable "attachment_1" in the POST, specify the file name and file type
        Dim preAttachment As String = dataBoundary   vbCrLf _
          "Content-Disposition: form-data; name=""attachment_1""; filename="""   fileName   """"   vbCrLf _
          "Content-Type: "   fileType   vbCrLf _
          vbCrLf

        'Convert this preAttachment string to bytes
        Dim preAttachmentBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(preAttachment)

        'Write this preAttachment string to the stream
        requestStream.Write(preAttachmentBytes, 0, preAttachmentBytes.Length)

        'Write the file as bytes to the stream by passing its exact location
        Using fileStream As New IO.FileStream(Server.MapPath(filePath   fileName), IO.FileMode.Open, IO.FileAccess.Read)

            Dim buffer(4096) As Byte
            Dim bytesRead As Int32 = fileStream.Read(buffer, 0, buffer.Length)

            Do While (bytesRead > 0)

                requestStream.Write(buffer, 0, bytesRead)
                bytesRead = fileStream.Read(buffer, 0, buffer.Length)

            Loop

        End Using

        'Create a variable named content in the POST, specify the attachment name and comment text
        Dim postAttachment As String = vbCrLf _
          dataBoundary   vbCrLf _
          "Content-Disposition: form-data; name=""content"""   vbCrLf _
          vbCrLf _
          "Action: comment"   vbLf _
          "Attachment: "   fileName   vbCrLf _
          "Text: Some description"   vbCrLf _
          vbCrLf _
          "--xYzZY--"

        'Convert postAttachment string to bytes
        Dim postAttachmentBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(postAttachment)

        'Write the postAttachment string to the stream
        requestStream.Write(postAttachmentBytes, 0, postAttachmentBytes.Length)

    End Using

    Dim response As Net.WebResponse = Nothing

    'Get the response from our REST request to RT
    'Required to capture response, without this Try-Catch attaching will fail
    Try
        response = request.GetResponse()

        Using responseStream As IO.Stream = response.GetResponseStream()

            Using responseReader As New IO.StreamReader(responseStream)

                Dim responseText = responseReader.ReadToEnd()

            End Using

        End Using

    Catch exception As Net.WebException

        response = exception.Response

        If (response IsNot Nothing) Then

            Using reader As New IO.StreamReader(response.GetResponseStream())

                Dim responseText = reader.ReadToEnd()

            End Using

            response.Close()

        End If

    Finally

        request = Nothing

    End Try

End Sub