I'm having trouble uploading some form data to an API endpoint in vb.net.
Example From Vendor:
curl -X POST -H 'Authorization: Token token=sfg999666t673t7t82'
-H 'Content-Type: multipart/form-data' -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
-F file=#/Users/user1/Downloads/download.jpeg -F file_name=nameForFile
-F is_shared=true -F targetable_id=1 -F targetable_type=Lead -X POST "https://domain.freshsales.io/api/documents"
VB.NET CODE
Shameless pulled from (Upload files with HTTPWebrequest (multipart/form-data))
Private Sub HttpUploadFile(ByVal filePath As String, ByVal fileParameterName As String, ByVal contentType As String, ByVal otherParameters As Specialized.NameValueCollection)
Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")
Dim newLine As String = System.Environment.NewLine
Dim boundaryBytes As Byte() = Text.Encoding.ASCII.GetBytes(newLine & "--" & boundary & newLine)
Dim request As Net.HttpWebRequest = Net.WebRequest.Create("https://domain.freshsales.io/api/documents")
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 = String.Format(formDataTemplate, key, newLine, otherParameters(key))
Dim formItemBytes As Byte() = Text.Encoding.UTF8.GetBytes(formItem)
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() = Text.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() = Text.Encoding.ASCII.GetBytes(newLine & "--" + boundary + "--" & newLine)
requestStream.Write(trailer, 0, trailer.Length)
End Using
Dim response As Net.WebResponse = Nothing
Try
response = request.GetResponse()
Using responseStream As IO.Stream = response.GetResponseStream()
Using responseReader As New IO.StreamReader(responseStream)
Dim responseText = responseReader.ReadToEnd()
Diagnostics.Debug.Write(responseText)
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()
Diagnostics.Debug.Write(responseText)
End Using
response.Close()
End If
Finally
request = Nothing
End Try
End Sub
Calling The Function
Here is my call:
Dim headers As NameValueCollection = New NameValueCollection()
headers.Add("Token", "token=youguessedit;")
Dim nvc As NameValueCollection = New NameValueCollection()
nvc.Add("is_shared", true)
nvc.Add("targetable_id", 1)
nvc.Add("targetable_type", "Lead")
HttpUploadFile("c:\test\file.pdf", "file", "application/pdf", nvc, headers);
I think part of my issue is in the way the headers are attached here:
Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}Content-Type: {3}{2}{2}"
In that the API endpoint is expecting file= and file_name= how can I correct the headers?
Can anyone point out where else I have gone wrong? Is there an easier way of doing this?
Here's a simple Console app example using HttpClient with a MultipartFormDataContent which takes care of all the headers and streaming the file, this example also works as-is thanks to Postman-Echo, if there's a requirement for additional headers (only Token is shown here) be sure to add them to the HttpClient.DefaultRequestHeaders
Dim response As New HttpResponseMessage
Dim path As String = "C:\\Temp\\upload.pdf"
Dim uri As New Uri("https://postman-echo.com/post")
Using form As New MultipartFormDataContent,
fs As New FileStream(path, FileMode.Open),
content As New StreamContent(fs),
httpClient As New HttpClient
form.Add(content)
httpClient.DefaultRequestHeaders.Add("Token", "Super Secret")
response = httpClient.PostAsync(uri, form).GetAwaiter.GetResult()
Console.WriteLine("Is Successfull: " & response.IsSuccessStatusCode)
End Using
EDIT: Cleaned up nested Using statements
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want sample codes for send files envelope for signing with specify template, recipients and once signed by all recipients file need to download. I have accessToken, account key with demo sandbox login,Could u provide exact code in vb.net better, if not, then in c#.
2 steps
1.Pass file with recipients (multiple recipients also)
2.Once signed by all recipients get back files instead replay in sender mail
regards,
Aravind
There are plenty of materials for what you are trying to accomplish. You can first start by downloading the c# launcher from https://github.com/docusign/code-examples-csharp. It has 31 examples. You can register for our webinars if you want to ask specific questions here https://www.docusign.com/company/events. You can start as well by reading our guides https://developers.docusign.com/docs/esign-rest-api/how-to/. Another place you can find useful information is https://www.docusign.com/blog/developers.
Here is a basic VB example for DocuSign.
You will need to add OAuth authentication to use it in production.
' DocuSign Builder example. Generated: Wed, 12 Aug 2020 16:35:59 GMT
' DocuSign Ⓒ 2020. MIT License -- https://opensource.org/licenses/MIT
' #see DocuSign Developer Center
Imports System.Net
Imports System.Text
Imports System.IO
Imports Newtonsoft.Json.Linq
Module Program
Const accountId As String = ""
Const accessToken As String = ""
Const baseUri As String = "https://demo.docusign.net"
Const documentDir = "Assets"
Function SendDocuSignEnvelope() As String ' RETURNS envelopeId
' Note: The JSON string constant uses the VB interpolated format.
' See https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/strings/interpolated-strings
' This format enables you to use the JSON as a template within your app, and
' replace values with interpolated/dynamic values. Remember that string values must be
' escaped per the JSON string rules. (Escape " as \")
Dim envelopeDefinition As String = $"{{
""emailSubject"": ""Please sign the attached document"",
""status"": ""sent"",
""documents"": [
{{
""name"": ""Example document"",
""fileExtension"": ""pdf"",
""documentId"": ""1""
}}
],
""recipients"": {{
""signers"": [
{{
""email"": ""signer_email#example.com"",
""name"": ""Signer's name"",
""recipientId"": ""1"",
""clientUserId"": ""1000"",
""tabs"": {{
""signHereTabs"": [
{{
""anchorString"": ""/sig1/"",
""anchorXOffset"": ""20"",
""anchorUnits"": ""pixels""
}}
]
}}
}}
]
}}
}}"
Dim documents = {
(mimeType:="application/pdf", filename:="Example document", documentId:="1", diskFilename:="anchorfields.pdf")
}
Dim url As String = $"{baseUri}/restapi/v2.1/accounts/{accountId}/envelopes"
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
Dim CRLF As String = vbCrLf
Dim boundary As String = "multipartboundary_multipartboundary"
Dim hyphens As String = "--"
postReq.Method = "POST"
postReq.KeepAlive = False
postReq.ContentType = $"multipart/form-data; boundary={boundary}"
postReq.Accept = "application/json"
postReq.Headers.Add("Authorization", $"Bearer {accessToken}")
postReq.UserAgent = "DS Builder tool VB"
' Send request as a multipart mime message with the
' documents included in binary format (not Base64 encoded)
Dim encoding As New UTF8Encoding
Dim byteData As Byte()
Dim stringBuffer As String
Dim postreqstream As Stream = postReq.GetRequestStream()
Dim postLength As Int32 = 0
Dim rawFilePath As String = Directory.GetCurrentDirectory() ' \\Mac\Home\www\VB_Example\VB_Example\bin\Debug\netcoreapp3.1\
Dim docFilePath As String = Path.GetFullPath(Path.Combine(rawFilePath, "..\..\..\" & documentDir & "\"))
Dim document As (mimeType As String, filename As String, documentId As String, diskFilename As String)
stringBuffer = 'Send preamble and JSON request
hyphens & boundary & CRLF & "Content-Type: application/json" &
CRLF & "Content-Disposition: form-data" & CRLF & CRLF & envelopeDefinition
byteData = encoding.GetBytes(stringBuffer)
postreqstream.Write(byteData, 0, byteData.Length)
postLength += byteData.Length
For Each document In documents
stringBuffer = CRLF & hyphens & boundary & CRLF & $"Content-Type: {document.mimeType}" &
CRLF & $"Content-Disposition: file; filename=""{document.filename}"";documentid={document.documentId}" & CRLF & CRLF
byteData = encoding.GetBytes(stringBuffer)
postreqstream.Write(byteData, 0, byteData.Length)
postLength += byteData.Length
' add the file's contents
Dim inputFile = File.Open(docFilePath & document.diskFilename, FileMode.Open)
' 1/2 Megabyte buffer. Dim statements specifies last index, so we subtract 1
Dim bufferSize As Integer = 1024 * 512
Dim bytes = New Byte(bufferSize - 1) {}
Dim bytesRead As Int32 = inputFile.Read(bytes, 0, bufferSize)
While bytesRead > 0
postreqstream.Write(bytes, 0, bytesRead)
postLength += bytesRead
bytesRead = inputFile.Read(bytes, 0, bufferSize)
End While
inputFile.Close()
Next
stringBuffer = CRLF & hyphens & boundary & hyphens & CRLF 'Send postamble
byteData = encoding.GetBytes(stringBuffer)
postreqstream.Write(byteData, 0, byteData.Length)
postLength += byteData.Length
postReq.ContentLength = postLength
Try
Dim postresponse As HttpWebResponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
Dim postreqreader = New StreamReader(postresponse.GetResponseStream())
Dim resultsJSON As String = postreqreader.ReadToEnd
Console.WriteLine($"Create envelope results: {resultsJSON}")
Dim resultsJObj As JObject = JObject.Parse(resultsJSON)
Dim envelopeId As String = resultsJObj("envelopeId")
Console.WriteLine($"EnvelopeId: {envelopeId}")
Return envelopeId
Catch Ex As WebException
Console.WriteLine($"Error while creating envelope! {Ex.Message}")
If Ex.Response IsNot Nothing Then
Console.WriteLine($"Error response: {New StreamReader(Ex.Response.GetResponseStream).ReadToEnd}")
End If
Return ""
End Try
End Function
Sub RecipientView(envelopeId As String)
Dim doRecipientView As Boolean = True
Dim recipientViewRequest As String = $"{{
""returnUrl"": ""https://docusign.com"",
""authenticationMethod"": ""none"",
""clientUserId"": ""1000"",
""email"": ""signer_email#example.com"",
""userName"": ""Signer's name""
}}"
Dim url As String = $"{baseUri}/restapi/v2.1/accounts/{accountId}/envelopes/{envelopeId}/views/recipient"
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
postReq.Method = "POST"
postReq.KeepAlive = False
postReq.ContentType = "application/json"
postReq.Accept = "application/json"
postReq.Headers.Add("Authorization", $"Bearer {accessToken}")
postReq.UserAgent = "DS Builder tool VB"
Dim encoding As New UTF8Encoding
Dim byteData As Byte()
Dim postreqstream As Stream = postReq.GetRequestStream()
byteData = encoding.GetBytes(recipientViewRequest)
postreqstream.Write(byteData, 0, byteData.Length)
postReq.ContentLength = byteData.Length
Try
Dim postresponse As HttpWebResponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
Dim postreqreader = New StreamReader(postresponse.GetResponseStream())
Dim resultsJSON As String = postreqreader.ReadToEnd
Dim resultsJObj As JObject = JObject.Parse(resultsJSON)
Dim viewUrl As String = resultsJObj("url")
Console.WriteLine("Create recipient view succeeded.")
Console.WriteLine("Open the signing ceremony's long URL within 5 minutes:")
Console.WriteLine(viewUrl)
Catch Ex As WebException
Console.WriteLine($"Error requesting recipient view! {Ex.Message}")
If Ex.Response IsNot Nothing Then
Console.WriteLine($"Error response: {New StreamReader(Ex.Response.GetResponseStream).ReadToEnd}")
End If
End Try
End Sub
' The mainline
Sub Main(args As String())
Console.WriteLine("Starting...")
Dim envelopeId As String = SendDocuSignEnvelope()
RecipientView(envelopeId)
Console.WriteLine("Done.")
End Sub
End Module
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
I'm trying to authenticate my application using OAuth2 and using the 'installed applications' flow (get auth-code and then request token). I'm getting a 400 bad request error when requesting the token on the GetResponse() line. My code is as follows:
Public Sub New()
Dim tokenRequest As WebRequest =
WebRequest.Create("https://accounts.google.com/o/oauth2/token")
Dim requestString As String = "code=<auth-code>" _
& "&client_id=<client_id>" _
& "&client_secret=<client_secret>" _
& "&redirect_uri=http://localhost" _
& "&grant_type=authorization_code"
byteArray = StrToByteArray(System.Web.HttpUtility.UrlEncode(requestString))
tokenRequest.Credentials = CredentialCache.DefaultCredentials
tokenRequest.Method = "POST"
tokenRequest.ContentLength = byteArray.Length
tokenRequest.ContentType = "application/x-www-form-urlencoded"
Dim dataStream As Stream = tokenRequest.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Console.WriteLine("Getting response...")
'Get response
Try
Dim response As WebResponse = tokenRequest.GetResponse()
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
Dim data As Stream = response.GetResponseStream
Array.Resize(byteArray, 4096)
Array.Clear(byteArray, 0, byteArray.Length)
data.Read(byteArray, 0, byteArray.Length)
response.Close()
Catch wex As WebException
Console.WriteLine("ERROR! : ")
Console.WriteLine(wex.Message)
Console.WriteLine(wex.Status)
Console.WriteLine(wex.Data)
Console.WriteLine(wex.InnerException.Message)
Console.WriteLine(wex.HelpLink)
End Try
End Sub
The specifics of the error are below:
The remote server returned an error: (400) Bad Request.
7
System.Collections.ListDictionaryInternal
System.NullReferenceException: Object reference not set to an instance of an obj
ect.
at GADownload.GoogleAnalytics..ctor() in ***.vb:line 86
at GADownload.Main1.Main(String[] args) in ****.vb:line 18
I've had a look at Google GetAccessToken : Bad Request 400 and Google GData .Net OAuthUtil.GetAccessToken 400 Bad Request but have not found a solution suited to this code. I have already checked all the solutions suggested and implemented them, but with no luck so far.
looks like you are not setting values for the parameters auth-code, client_id or client_secret.
you can debug these parameters with a curl command to see if this is the source of the problem. e.g.
curl -X POST -d "code=<auth-code>&client_id=<client_id>&client_secret=<client_secret>"&grant_type=authorization_code" http://localhost:8000/auth/token
Can you try URL encoding redirect_uri
redirect_uri=http://localhost
That is the only thing I'm seeing on your code vs. mine. Here's my code that is similar in vb and working
Dim sb As New StringBuilder
sb.Append("code=").Append(Request.QueryString("code")) _
.Append("&client_id=") _
.Append(Session.Item("ClientID")) _
.Append("&client_secret=") _
.Append(Session.Item("ClientSecret")) _
.Append("&redirect_uri=") _
.Append(HttpUtility.UrlEncode("http://localhost/1.aspx")) _
.Append("&grant_type=authorization_code")
Dim requestGoogle As HttpWebRequest =
WebRequest.Create("https://accounts.google.com/o/oauth2/token")
requestGoogle.Method = "POST"
requestGoogle.ContentType = "application/x-www-form-urlencoded"
requestGoogle.ContentLength = sb.Length
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(sb.ToString)
sb.Clear()
requestGoogle.GetRequestStream.Write(byteArray, 0, byteArray.Length)
byteArray = Nothing
Dim responseGoogle As HttpWebResponse = requestGoogle.GetResponse()
If responseGoogle.StatusCode = HttpStatusCode.OK Then
Dim sr As StreamReader = _
New StreamReader(responseGoogle.GetResponseStream)
Dim s As String = sr.ReadToEnd
sr.Close()
responseGoogle.GetResponseStream.Close()
requestGoogle.GetRequestStream.Close()
'Response.Write(s)
End If
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}"
Holy wow I've tried everything from writing my own headers to converting C# examples and I still can't get past the 400 Bad Request error when uploading a photo.
I have every possible permission added and my token is correct.
I can post status updates to my feed, I just can't get images uploaded. Here are two different approaches I tried, and both give me 400 Bad Request...
1
Dim myReq As HttpWebRequest
Dim myRes As HttpWebResponse
Dim encoding As New System.Text.ASCIIEncoding()
Dim postData As String
Dim data() As Byte
Dim sr As StreamReader
Dim imagedata As String
imagedata = File.OpenText("C:\ebay00042-1.jpg").ReadToEnd()
postData += "access_token=MY_TOKEN_HERE_29ZB51pPizthxX5lhmst3MZC7hYXQhW8ZB8e7sVVLzEaN8ZCZAzAgrzk1pisw3ZCtK5lwMMTZBUhe07xTsQvfeHosA1GFUAZDZD&message=this is a test123&source=" & imagedata 'File.ReadAllBytes(photoPath)
data = encoding.GetBytes(postData)
myReq = WebRequest.Create("https://graph.facebook.com/380406275386560/photos")
DirectCast(myReq, System.Net.HttpWebRequest).UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"
myReq.Method = "POST"
myReq.ContentType = "application/x-www-form-urlencoded"
myReq.ContentLength = data.Length
Dim myStream As Stream = myReq.GetRequestStream
myStream.Write(data, 0, data.Length)
myStream.Close()
myRes = myReq.GetResponse
sr = New StreamReader(myRes.GetResponseStream)
Dim strHTML As String = sr.ReadToEnd
2, trying to create my own headers..
Dim myReq As HttpWebRequest
Dim myRes As HttpWebResponse
Dim encoding As New System.Text.ASCIIEncoding()
Dim data() As Byte
Dim sr As StreamReader
Dim boundary As String = "----------" + DateTime.Now.Ticks.ToString("x")
Dim sb As StringBuilder = New StringBuilder("")
sb.Append("----------").Append(boundary).Append("\r\n")
sb.Append("Content-Disposition: form-data; name=""access_token""").Append("\r\n")
sb.Append("\r\n")
sb.Append("MY_TOKEN_HERE_MZC7hYXQhW8ZB8e7sVVLzEaN8ZCZAzAgrzk1pisw3ZCtK5lwMMTZBUhe07xTsQvfeHosA1GFUAZDZD").Append("\r\n")
sb.Append("----------").Append(boundary).Append("\r\n")
sb.Append("Content-Disposition: form-data; name=""message""").Append("\r\n")
sb.Append("\r\n")
sb.Append("Testttt").Append("\r\n")
sb.Append("----------").Append(boundary)
sb.Append("Content-Disposition: file; name=""source"" filename=""ebay00042-1.jpg""").Append("\r\n")
sb.Append("Content-Type: image/jpeg).Append(\r\n")
'sb.Append("Content-Transfer-Encoding: binary").Append("\r\n")
sb.Append("\r\n")
sb.Append(File.OpenText("C:\ebay00042-1.jpg").ReadToEnd()).Append("\r\n")
sb.Append("----------").Append(boundary).Append("----------").Append("\r\n")
'txtCaption.Text = sb.ToString
data = encoding.GetBytes(sb.ToString)
myReq = WebRequest.Create("https://graph.facebook.com/380406275386560/photos")
DirectCast(myReq, System.Net.HttpWebRequest).UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"
myReq.Method = "POST"
myReq.ContentType = "multipart/form-data; boundary=" + boundary
'myReq.ContentType = "application/x-www-form-urlencoded"
myReq.ContentLength = data.Length
Dim myStream As Stream = myReq.GetRequestStream
myStream.Write(data, 0, data.Length)
myStream.Close()
myRes = myReq.GetResponse
sr = New StreamReader(myRes.GetResponseStream)
Dim strHTML As String = sr.ReadToEnd
Any help would be greatly appreciated!
I don't know anything about Facebook's API, but if I were you I'd have a good look at http://csharpsdk.org/
If I had to send an image based on the info you provided, it would look something like this :
' Request URL, image file to send, token and result HTML buffer
Dim reqUrl As String = "https://graph.facebook.com/380406275386560/photos"
Dim imageData As Byte() = File.ReadAllBytes("C:\ebay00042-1.jpg")
Dim token As String = "MY_TOKEN_HERE"
Dim strHtml As String = ""
' Request
Dim request As WebRequest = WebRequest.Create(reqUrl)
request.Headers.Add("access_token", token)
request.Method = "POST"
' set *correct* content type
request.ContentType = "image/jpeg"
' write image data to request stream
Using str = request.GetRequestStream()
str.Write(imageData, 0, imageData.Length)
End Using
' response
Dim response As WebResponse = request.GetResponse()
' HTTP Status
Dim status As Integer = CType(response, HttpWebResponse).StatusCode
If status = 200 Then
' success
Using reader As New StreamReader(response.GetResponseStream())
strHtml = reader.ReadToEnd()
End Using
Else
' oops
End If
Hope that helps.