Twitter upload/media Append - vb.net

I just can't wrap my mind around how to do the append step. I've already done the INIT part without trouble but I don't understand how to do the next step.
What I'm doing now : I build a authorization header with only the oauth parameters and the signature base too, then I put the required parameters into the body request : command=APPEND, media_id from the INIT method, media with the raw binary image, and segment_index=0 because I have to send only one request since the size of my image is never more than 30 kB.
I have tried the following:
Dim oHttpWebRequest As HttpWebRequest
Dim oHttpWebResponse As HttpWebResponse
Dim oStream As Stream
Dim newLine As String = System.Environment.NewLine
Dim mediaId = getINITresponse()
Try
oHttpWebRequest = DirectCast(WebRequest.Create("https://upload.twitter.com/1.1/media/upload.json"), HttpWebRequest)
Dim sBody As String = buildHeader(twitter, sAuth)
oHttpWebRequest.Headers.Add("Authorization", sBody)
oHttpWebRequest.Method = "POST"
Dim sBoundary As String = DateTime.Now.Ticks.ToString("x")
Dim sStartBoundary As String = "--" + sBoundary + newLine
Dim sEndBoundary As String = newLine + "--" + sBoundary + "--" + newLine
oHttpWebRequest.ContentType = "multipart/form-data; boundary=" + sBoundary
Dim sBodyData As String = ""
Dim srequestString As New StringBuilder()
sBodyData = "command=APPEND&media_id=" + mediaId + "&segment_index=0&media="
srequestString.AppendLine(sStartBoundary + "Content-Disposition: form-data; name=""media""; filename=""image.jpg""" + newLine)
srequestString.AppendLine(Encoding.Default.GetString(getBinaryFileFromPath(sFicName)))
srequestString.AppendLine(newLine + sEndBoundary + newLine)
Dim postData As Byte()
postData = Text.Encoding.UTF8.GetBytes(sBodyData)
Dim postDataBytes As Byte()
postDataBytes = Text.Encoding.UTF8.GetBytes(srequestString.ToString())
Dim byteResult() As Byte = postData.Concat(postDataBytes).ToArray()
oHttpWebRequest.ContentLength = byteResult.Length
Using requestStream = oHttpWebRequest.GetRequestStream()
requestStream.Write(byteResult, 0, byteResult.Length)
requestStream.Close()
End Using
oHttpWebResponse = DirectCast(oHttpWebRequest.GetResponse(), HttpWebResponse)
oStream = oHttpWebResponse.GetResponseStream()
Return New StreamReader(oStream, Encoding.UTF8).ReadToEnd()
Catch wex As WebException 'Exception venant du serveur distant
Return New StreamReader(wex.Response.GetResponseStream()).ReadToEnd()
End Try
My Init part is working and I save the media_id and use it for the Append part. My image is no more than 30 kB so it's not a problem of size.
Twitter respond me with the status : 400 Bad Request.
I don't know what I am doing wrong. Sorry for my bad english!

I find the answer:
sBodyData = "command=APPEND&media_id=" + mediaId + "&segment_index=0&media="
I was making my body data as if I was sending a request with ContentType=application/x-www-form-urlencoded.
So I used both of the contentType in the same request and of course it wasn't working. Now it looks like that:
Dim newLine As String = System.Environment.NewLine
srequestString.AppendLine(sStartBoundary + "Content-Disposition: form-data; name=""command""" + newLine)
srequestString.AppendLine("APPEND")
srequestString.AppendLine(sStartBoundary + "Content-Disposition: form-data; name=""media_id""" + newLine)
srequestString.AppendLine(mediaId)
srequestString.AppendLine(sStartBoundary + "Content-Disposition: form-data; name=""media""" + newLine)
srequestString.AppendLine(Encoding.Default.GetString(getBinaryFileFromPath(sFileName)))
srequestString.AppendLine(sStartBoundary + "Content-Disposition: form-data; name=""segment_index""" + newLine)
srequestString.AppendLine("0")
srequestString.AppendLine(sEndBoundary)

Related

Prestashop - Unable to upload a new image product with the prestashop 1.6 webservice

I'm trying to upload a new image for a product with the prestashop webservice through a vb .net application, but I get the following error message:
"Unable to save this image".
The URL used to upload the image is this: http://localhost/prestashop/api/images/products/1
And the source code of the function that make the request is this:
Public Sub executeAddImage(ByVal resource As String, ByVal id As String, ByVal imageToAdd As Image)
Dim response As String = Nothing
Try
Dim ms As New MemoryStream()
imageToAdd.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim byteArray As Byte() = ms.ToArray()
Dim requestUrl As String = Me.WebServiceURL & "/" & resource & "/" & id
MsgBox(requestUrl)
Dim webRequest As HttpWebRequest = DirectCast(System.Net.WebRequest.Create(requestUrl), HttpWebRequest)
webRequest.Method = WebServicePrestashop.CRUDMethod.Create
'webRequest.ContentType = "image/jpeg"
webRequest.ContentType = "application/x-www-form-urlencoded"
webRequest.Credentials = New NetworkCredential(Me.LoginName, WebServicePrestashop._password)
webRequest.ContentLength = byteArray.Length
MsgBox(byteArray.Length)
' Get the request stream
Using dataStream As Stream = webRequest.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
End Using
' Get the response
Using webResponse As HttpWebResponse = DirectCast(webRequest.GetResponse(), HttpWebResponse)
If webResponse.StatusCode = HttpStatusCode.OK Then
Using reader As New StreamReader(webResponse.GetResponseStream(), Encoding.UTF8)
Dim imageNew As Image = Image.FromStream(webResponse.GetResponseStream())
End Using
End If
End Using
Catch ex As WebException
MsgBox(ex.Message.ToString())
Dim reader As New StreamReader(ex.Response.GetResponseStream)
MsgBox(reader.ReadToEnd)
End Try
End Sub
I'm using the HTTP POST method, and the POST content is the bynary content of the new image.
How can I fix it?.
Here the solution.
I think the key is that I must write the body of the webrequest programatically adding to the stream of the webrequest the boundary (in binary array format), the Content-Type chain (in binary array format) and the content of the image to upload (in binary array format).
Public Sub executeAddImage(ByVal resource As String, ByVal id As String, ByVal imageToAdd As Byte())
Dim response As String = Nothing
Try
Dim requestUrl As String = "urlShop" & "/api/" & resource & "/" & id
MsgBox(requestUrl)
Dim webRequest As HttpWebRequest = DirectCast(System.Net.WebRequest.Create(requestUrl), HttpWebRequest)
webRequest.KeepAlive = True
webRequest.Credentials = New NetworkCredential(Me.LoginName, WebServicePrestashop._password)
webRequest.ContentLength = imageToAdd.Length
webRequest.Method = "POST"
webRequest.ContentType = "image/jpeg"
Dim boundary As String = "----" & DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture)
webRequest.ContentType = "multipart/form-data; boundary=" & boundary
Dim beginPostData = "--" & boundary & vbCrLf & "Content-Disposition: form-data; name=""image""; filename=""torrente.jpg""" & _
vbCrLf & "Content-Type: image/jpeg" & vbCrLf & vbCrLf
Dim boundaryBytes = System.Text.Encoding.ASCII.GetBytes(vbCrLf & "--" & boundary & "--" & vbCrLf)
Dim beginPostDataBytes = System.Text.Encoding.ASCII.GetBytes(beginPostData)
webRequest.ContentLength = beginPostData.Length + imageToAdd.Length + boundaryBytes.Length
' Get the request stream
Using dataStream As Stream = webRequest.GetRequestStream()
dataStream.Write(beginPostDataBytes, 0, beginPostDataBytes.Length)
dataStream.Write(imageToAdd, 0, imageToAdd.Length)
dataStream.Write(boundaryBytes, 0, boundaryBytes.Length)
End Using
' Get the response
Using webResponse As HttpWebResponse = DirectCast(webRequest.GetResponse(), HttpWebResponse)
If webResponse.StatusCode = HttpStatusCode.OK Then
Using reader As New StreamReader(webResponse.GetResponseStream())
response = reader.ReadToEnd()
MsgBox(response)
End Using
End If
End Using
Catch ex As WebException
MsgBox(ex.Message.ToString())
Dim reader As New StreamReader(ex.Response.GetResponseStream)
MsgBox(reader.ReadToEnd)
End Try
End Sub

HttpRequest Exception Header section VB.NET

I'm trying to upload a file with the following code, but when I upload a file raises an exception: Header section has more than 10240 bytes (maybe it is not properly terminated)
I try with this but isn't work: WebRequest POST with both file and parameters
Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")
Dim newLine As String = System.Environment.NewLine
Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes(newLine & "--" & boundary & newLine)
Dim request As Net.HttpWebRequest = Net.WebRequest.Create(uri)
request.ContentType = "multipart/form-data; boundary=" & boundary
request.Method = "POST"
request.KeepAlive = True
Using requestStream As IO.Stream = request.GetRequestStream()
Dim formDataTemplate As String = "Content-Disposition: form-data; name=""{0}""{1}{1}{2}"
For Each key As String In otherParameters.Keys
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
Dim formItem As String
Dim formItemBytes As Byte()
If key = "file" Then
formItemBytes = StreamFile(otherParameters(key))
Else
formItem = String.Format(formDataTemplate, key, newLine, otherParameters(key))
formItemBytes = Encoding.UTF8.GetBytes(formItem)
End If
requestStream.Write(formItemBytes, 0, formItemBytes.Length)
Next key
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}Content-Type: {3}{2}{2}"
Dim header As String = String.Format(headerTemplate, fileParameterName, filePath, newLine, contentType)
Dim headerBytes As Byte() = Encoding.UTF8.GetBytes(header)
requestStream.Write(headerBytes, 0, headerBytes.Length)
Using fileStream As New IO.FileStream(filePath, 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
Dim trailer As Byte() = Encoding.ASCII.GetBytes(newLine & "--" + boundary + "--" & newLine)
requestStream.Write(trailer, 0, trailer.Length)
End Using
Dim response As Net.WebResponse = request.GetResponse()
EDIT:
I try with two options and not work:
Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2} Content-Type: {3}{2}{2}"
Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}" & newLine & "Content-Type: {3}{2}{2}"

VB.NET - How To Get Raw Image Data To String

How would I get raw image data to a String in VB.NET similar to the following:
J©õݨe‚Lnž¿Ëã/ǧúÐ5ý¼C÷Cý>ß’t;fm—=Äw:�/E±ËÙÏ$á#%Pc>× Šgw.²Ab“:ÅÓù:ϯÌh6à€Z§Ó‚g£®hÚD6¨Ø^Ú2ô`ä¨L�YÆÄÅCX#I“ÈÌãj¦L˜•’|¥�Eb¡ëQ–¤Ú, 3\UzL öÔoj4�•±’u«c¼#„oÕ`îF>·o—ŠûÅ«ÎÑ™¶Ç˜ýº*i°œÈVŒ�Qû”Ñ[.�ÔmçE•ì¦eNCh�Ù
é§�É$m¿ôš"»ÌNæ(VÌmp›F¹XÈ88™ªüµ…d•XµÔÜ#�ˆŠv‘º‚F‚§Yûb
My current code is:
Dim FileName As String = "Image.jpg"
Dim ImageData() As Byte = File.ReadAllBytes(ProfileImagePath)
Dim NewImageData As String = Convert.ToBase64String(ImageData)
This returns the Base64 code but I am trying to get the actual raw data like in the example above so that I can POST to a multipart upload form which also posts in this way.
My full code for the upload being:
Dim boundary As String = "-----------------------------" & DateTime.Now.Ticks.ToString("x")
Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://www.mysite.com/upload.php"), HttpWebRequest)
req.Method = "POST"
req.ContentType = "multipart/form-data; boundary=" & "---------------------------" & DateTime.Now.Ticks.ToString("x")
req.KeepAlive = False
Dim builder As New StringBuilder()
builder.Append(boundary & vbCrLf & "Content-Disposition: form-data; name=""variable1""" & vbCrLf & vbCrLf & "1" & vbCrLf)
builder.Append(boundary & vbCrLf & "Content-Disposition: form-data; name=""file""; filename=""" & FileName & """" & vbCrLf)
builder.Append("Content-Type: application/octet-stream")
builder.Append(vbCrLf & vbCrLf)
' Add Photo Here
If UpdateImage = True Then
' Load Image
Dim ImageData() As Byte = File.ReadAllBytes(ProfileImagePath)
Dim NewImageData As String = Convert.ToBase64String(ImageData)
' Add Image To Header
builder.Append(NewImageData)
builder.Append(vbCrLf)
Else
builder.Append(vbCrLf)
End If
builder.Append(boundary & vbCrLf & "Content-Disposition: form-data; name=""save""" & vbCrLf & vbCrLf & "save")
' Footer Bytes
Dim close As Byte() = Encoding.UTF8.GetBytes("--")
Dim postHeader As String = builder.ToString()
Dim postHeaderBytes As Byte() = Encoding.UTF8.GetBytes(postHeader)
Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes(vbCrLf & boundary & "--" & vbCrLf)
Dim length As Long = postHeaderBytes.Length + boundaryBytes.Length
req.ContentLength = length
Dim requestStream As Stream = req.GetRequestStream()
Dim fulllength As Integer = postHeaderBytes.Length + boundaryBytes.Length
' Write out our post header
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length)
' Write out the trailing boundary
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
Dim responce As WebResponse
responce = req.GetResponse()
requestStream.Close()
Dim s As Stream = responce.GetResponseStream()
Dim sr As New StreamReader(s)
Dim Content As String = sr.ReadToEnd()
This returns the Base64 code but I am trying to get the actual raw data like in the example above
The "actual raw data" isn't text data so you shouldn't put it in a string at all; at least not without something like base64.
If you want to post binary data, then either use base64 or post it as raw bytes, but not as text. Your data is not UTF-8-encoded text, so don't try to use it as if it were.
(I can't remember the details of multi-part form data; if you can specify a part length before the part itself, then you should be fine to include the binary data directly. If it's always just delimited by some separator, then you may want to use base64 instead.)

Uploading Image MultiPart Form HTTPWebRequest - Getting Image Data To String?

I am trying to upload a multi-part form with HTTPWebRequest & all is ok until I added an image to upload, mainly I am trying to do exactly the same request as a browser makes which looks like this:
-----------------------------41184676334
Content-Disposition: form-data; name="file"; filename="guitar tape.jpg"
Content-Type: image/jpeg
IMAGEDATAHERE
-----------------------------41184676334
Content-Disposition: form-data; name="save"
save
-----------------------------41184676334--
I am lost on how to format / read the image to set it into the request that I am making below:
Dim boundary As String = "-----------------------------" & DateTime.Now.Ticks.ToString("x")
Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://www.mysite.com/upload.php"), HttpWebRequest)
req.Method = "POST"
req.ContentType = "multipart/form-data; boundary=" & "---------------------------" & DateTime.Now.Ticks.ToString("x")
req.KeepAlive = False
Dim builder As New StringBuilder()
builder.Append(boundary & vbCrLf & "Content-Disposition: form-data; name=""variable1""" & vbCrLf & vbCrLf & "1" & vbCrLf)
builder.Append(boundary & vbCrLf & "Content-Disposition: form-data; name=""file""; filename=""" & FileName & """" & vbCrLf)
builder.Append("Content-Type: application/octet-stream")
builder.Append(vbCrLf & vbCrLf)
' Add Photo Here
If UpdateImage = True Then
' Load Image
Dim ImageData As System.Drawing.Image
Dim fs As New System.IO.FileStream(ImagePath, System.IO.FileMode.Open)
ImageData = Image.FromStream(fs)
fs.Close()
' Add Image To Header
builder.Append(ImageData)
builder.Append(vbCrLf)
Else
builder.Append(vbCrLf)
End If
builder.Append(boundary & vbCrLf & "Content-Disposition: form-data; name=""save""" & vbCrLf & vbCrLf & "save")
' Footer Bytes
Dim close As Byte() = Encoding.UTF8.GetBytes("--")
Dim postHeader As String = builder.ToString()
Dim postHeaderBytes As Byte() = Encoding.UTF8.GetBytes(postHeader)
Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes(vbCrLf & boundary & "--" & vbCrLf)
Dim length As Long = postHeaderBytes.Length + boundaryBytes.Length
req.ContentLength = length
Dim requestStream As Stream = req.GetRequestStream()
Dim fulllength As Integer = postHeaderBytes.Length + boundaryBytes.Length
' Write out our post header
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length)
' Write out the trailing boundary
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
Dim responce As WebResponse
responce = req.GetResponse()
requestStream.Close()
Dim s As Stream = responce.GetResponseStream()
Dim sr As New StreamReader(s)
Dim Content As String = sr.ReadToEnd()
At the moment it is simply posting "System.Drawing.Bitmap" as the image data but I am not sure how to get the same raw data for the image that looks like this:
J©õݨe‚Lnž¿Ëã/ǧúÐ5ý¼C÷Cý>ß’t;fm—=Äw:�/E±ËÙÏ$á#%Pc>× Šgw.²Ab“:ÅÓù:ϯÌh6à€Z§Ó‚g£®hÚD6¨Ø^Ú2ô`ä¨L�YÆÄÅCX#I“ÈÌãj¦L˜•’|¥�Eb¡ëQ–¤Ú, 3\UzL  öÔoj4�•±’u«c¼#„oÕ`îF>·o—ŠûÅ«ÎÑ™¶Ç˜ýº*i°œÈVŒ�Qû”Ñ[.�ÔmçE•ì¦eNCh�Ù
é§�É$m¿ôš"»ÌNæ(VÌmp›F¹XÈ88™ªüµ…d•XµÔÜ#�ˆŠv‘º‚F‚§Yûb
Any ideas on how I could do this or would I need to change my methods?
builder.Append(ImageData)
is not correct. you need read the image as byte, then add the byte[] to the multipart post.
see details at Using HttpWebRequest to POST data/upload image using multipart/form-data
and make sure use a http sniffer (i.e. fiddler) to see what it is actually sending.
first, load image into byte array, then convert it to base64:
imgBase64 = Convert.ToBase64String(my_image_byte_array)
My "OpenFileDialog" name is "file". When a "button" is clicked it will show a pop up dialog for selecting jpg, jpeg, png image files, it can also add bmp or any image file type. Then after the selection of a image file it will show on "PictureBox" i name it as "picboxProfileID".
In Visual Basic:
file.Filter = "image file (*.jpg, *.jpeg, *.png) | *.jpg; *.jpeg; *.png | all files (*.*) | *.*"
If (file.ShowDialog <> Windows.Forms.DialogResult.Cancel) Then
picboxProfileID.Image = Image.FromFile(file.FileName)
picboxProfileID.ImageLocation = file.FileName
txtName.Text = file.FileName
My.Computer.Network.UploadFile(file.FileName, "http://localhost/VTVTS/uploadImageSample.php")
Else
picboxProfileID.Image = Nothing
End If
The destination of the file uploaded will be uploaded on the "images/" of the parent folder php file created.
In PHP:
<?php
$response = array();
$image = $_FILES['file'];
$imageName = $image['name'];
$imageTmpName = $image['tmp_name'];
$imageSize = $image['size'];
$imageError = $image['error'];
$imageType = $image['type'];
$fileExt = explode('.', $imageName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if(in_array($fileActualExt, $allowed)){
$fileNameNew = uniqid('', true).".".$fileActualExt;
$fileDestination = 'images/'.$fileNameNew;
$newDestination = move_uploaded_file($imageTmpName, $fileDestination);
$response['error'] = false;
$response['message'] = "Upload Image Successful";
}else{
$response['error'] = true;
$response['message'] = "You cannot upload files of this type!";
}
echo json_encode($response);
Happy Coding!

Attachments using REST WebService and VB.NET

I am currently developing an application using VB.NET in which I am using the REST WebServices. I have been able to do the basics with REST, however, I have not been able to add an attachment (more specifically upload a file, using REST which gets attached). I have done extensive research online, but so far I have not been able to find any working examples in VB.NET. To actually upload the data I use System.Net.WebClient. The following VB.NET code does the important work:
Dim Client As New System.Net.WebClient
Dim postBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(postString)
Client.UploadData(URL, "POST", postBytes)
A simplified version of my URL is as follows:
"../REST/1.0/ticket/" + ticketNumber + "/comment?user=" + userName + "&pass=" + password
Finally, an example of the content that I post is:
postString = "content=Text: RT Test" + vbLf + "Action: Comment" + vbLf + "Attachment: examplefile.jpg" + vbLf + "attachment_1="
As you can see, the postString is converted to bytes and then uploaded to the server. However, I do not know where or how I should be posting the raw attachment itself. The documentation for the service we are specifically using states to use a variable "attachment_1," which I added to the postString variable, but I am not sure what the next step should be. Should the file be converted into bytes and appended to the postBytes variable? I attempted something like this but I received an error saying that no attachment was found for examplefile.jpg.
Thanks for your help!
We could not use Client.UploadData(...) and had to convert the entire post to bytes, starting with the POST fields before the attachment, then the attachment itself, and finally the remainder of the POST fields.
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