how to Sending SMS through VB.NET - vb.net

I tried to send sms
it was using textlocal.in
this is the code i tried
Public Function SendSms(sender As Object, e As EventArgs) Handles Button1.Click
Dim apikey = txtAPI.Text
Dim message = txtMsg.Text
Dim numbers = txtNum.Text
Dim strPOST As String
Dim senderName = txtSend.Text
Dim url As String = "https://api.textlocal.in/send/?"
strPOST = url + "apikey=" + apikey _
+ "&numbers=" + numbers _
+ "&message=" + WebUtility.UrlEncode(message) _
+ "&sender=" + sender
Dim request As WebRequest = WebRequest.Create(strPOST)
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(strPOST)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
Console.WriteLine(responseFromServer)
Console.ReadLine()
reader.Close()
dataStream.Close()
response.Close()
If responseFromServer.Length > 0 Then
Return responseFromServer
Else
Return CType(response, HttpWebResponse).StatusDescription
End If
End Function
it is saying Operator '+' is not defined for string "https://api.textlocal.in/send/?a" and type 'Button

In this code sender is the Button that raises the event:
Public Function SendSms(sender As Object
^^^^^^
It is not the phone number of the person sending the message. Replace sender with senderName on this line:
strPOST = url + "apikey=" + apikey _
+ "&numbers=" + numbers _
+ "&message=" + WebUtility.UrlEncode(message) _
+ "&sender=" + sender
^^^^^^^
Do not use + to concatenate strings in vb unless you know exactly what it is doing
Use & to concatenate strings, but in this case I would recommend you use string formatting

Related

How to call the API POST method by passing the base64 image with the urlencoded in VB?

I'm trying to call the API post method by passing the image file (converting into base64 format).
I am able to call successfully in POSTMAN as per below:
But I'm unable to call in vb code and got the error message.
Below is my code in vb:
Function CallAPI(ByVal URL As String, ByVal Data As String) As String
Dim dataStream() As Byte = Encoding.UTF8.GetBytes(Data)
Dim request As String = (URL)
Dim webRequest As WebRequest = WebRequest.Create(request)
webRequest.Method = "POST"
webRequest.ContentType = "application/x-www-form-urlencoded"
webRequest.ContentLength = dataStream.Length
Dim newStream As Stream = webRequest.GetRequestStream
' Send the data.
newStream.Write(dataStream, 0, dataStream.Length)
newStream.Close()
Dim Response As WebResponse = webRequest.GetResponse
Dim Reader As New StreamReader(Response.GetResponseStream)
Dim Results As String = Reader.ReadToEnd
Return Results
End Function
'Below is the code to convert the image file to base64 format:
Dim imgBase64 As String = ""
Dim imgBase64FilePath As String = ""
imgBase64FilePath = State.ApplicationSettings.WebPath().ToString() + "Photos\" + CStr(Fields.Item("EMPE_ID").Value) + "_" + epFields.GetValue("COMP_CODE").ToString().ToUpper() + ".jpg"
If helper.IsExists(imgBase64FilePath) Then
imgBase64 = ConvertFileToBase64(imgBase64FilePath)
End If
'I call the above function as per below:
Dim url = "http://" + deviceIP + "/face/create"
Dim data As String = "pass=" + devicePW + "&personId=" + CStr(Fields.Item("CARD_NO").Value) + "&faceId=" + CStr(Fields.Item("CARD_NO").Value) + "&imgBase64=" + imgBase64
Dim response As String = CallAPI(url, data)
Below is the error response:
{"code":"2000","msg":"200003, bad base-64","result":1,"success":false}
May I know which part is wrong?
Please advise me.
Thanks in Advance.

how to add filters on vb HttpWebRequest

This code, is working perfectly (getting data with web request) :
Protected Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim oauth_token = "8e269b44b2d7d73eb0b46112af5f4xxx"
Dim oauth_token_secret = "80da1edadcba1e66e47d2e20f075cxxx"
Dim oauth_consumer_key = "3626311748bcf2072da2bd475fccfxxx"
Dim oauth_consumer_secret = "0cbb0df8d840e22b96d4f80449e7exxx"
Dim oauth_version = "1.0"
Dim oauth_signature_method = "HMAC-SHA1"
Dim oauth_nonce = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
Dim timeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
Dim oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
Dim resource_url = "http://www.inart.com/api/rest/products/store/1"
Dim baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}"
Dim baseString = String.Format(baseFormat, oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_token, oauth_version)
baseString = String.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString))
Dim compositeKey = String.Concat(Uri.EscapeDataString(oauth_consumer_secret), "&", Uri.EscapeDataString(oauth_token_secret))
Dim oauth_signature As String
Using hasher As New HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey))
oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)))
End Using
Dim headerFormat = "OAuth oauth_nonce=""{0}"", oauth_signature_method=""{1}"", " + "oauth_timestamp=""{2}"", oauth_consumer_key=""{3}"",
" + "oauth_token=""{4}"", oauth_signature=""{5}"", " + "oauth_version=""{6}"""
Dim authHeader = String.Format(headerFormat, Uri.EscapeDataString(oauth_nonce), Uri.EscapeDataString(oauth_signature_method), Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_consumer_key), Uri.EscapeDataString(oauth_token), Uri.EscapeDataString(oauth_signature), Uri.EscapeDataString(oauth_version))
ServicePointManager.Expect100Continue = True
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(resource_url), HttpWebRequest)
request.Headers.Add("Authorization", authHeader)
request.Method = "GET"
request.ContentType = "application/json"
request.Accept = "application/json"
Try
Dim response As WebResponse = request.GetResponse()
Dim datastream As Stream = response.GetResponseStream
Dim reader As StreamReader = New StreamReader(datastream)
Dim responsefromserver As String = reader.ReadToEnd
If responsefromserver = Nothing Then
TextBox1.Text = "No response from server"
Else
Dim json As String = responsefromserver
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
Dim output As String = ""
Dim successReq As Boolean = False
Dim avDom As String = ""
Dim counter As Integer = 0
For Each item As JProperty In data
item.CreateReader()
output += "|-" & item.Name.ToString & " : " & item.Value.ToString & "-"
output += Environment.NewLine
counter += 1
Next
TextBox1.Text = output
TextBox1.Text += Environment.NewLine + counter.ToString
reader.Close()
response.Close()
End If
Catch ex As Exception
TextBox1.Text = ex.Message.ToString
End Try
End Sub
When i try to add some filters, it fails. for example, I try to add the limit filter this way : Dim resource_url = "http://www.inart.com/api/rest/products/store/1?limit=1".
I am sure that the filter is ok because i tried at postman application and it is working! see print screen
What should I change or add?
Thank you.
Dim url As String = "http://www.inart.com/api/rest/products/store/1?limit=1&page=2"
Dim oauthconsumerkey As String = "3626311748bcf2072da2bd475fccssss"
Dim oauthconsumersecret As String = "0cbb0df8d840e22b96d4f80449sssss"
Dim oauthtoken As String = "8e269b44b2d7d73essss2af5f454e"
Dim oauthtokensecret As String = "80da1edadcba1e66e47d2e2sssss"
Dim oauthsignaturemethod As String = "HMAC-SHA1"
Dim oauthversion As String = "1.0"
Dim oauthnonce As String = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
Dim timeSpan As TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
Dim oauthtimestamp As String = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
Dim basestringParameters As SortedDictionary(Of String, String) = New SortedDictionary(Of String, String)()
basestringParameters.Add("limit", "1")
basestringParameters.Add("page", "2")
basestringParameters.Add("oauth_version", oauthversion)
basestringParameters.Add("oauth_consumer_key", oauthconsumerkey)
basestringParameters.Add("oauth_nonce", oauthnonce)
basestringParameters.Add("oauth_signature_method", oauthsignaturemethod)
basestringParameters.Add("oauth_timestamp", oauthtimestamp)
basestringParameters.Add("oauth_token", oauthtoken)
Dim baseString As StringBuilder = New StringBuilder()
baseString.Append("GET" & "&")
baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split("?"c)(0)) & "&"))
For Each entry As KeyValuePair(Of String, String) In basestringParameters
baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key & "=" + entry.Value & "&")))
Next
Dim finalBaseString As String = baseString.ToString().Substring(0, baseString.Length - 3)
Dim signingKey As String = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) & "&" + EncodeCharacters(Uri.EscapeDataString(oauthtokensecret))
Dim hasher As HMACSHA1 = New HMACSHA1(New ASCIIEncoding().GetBytes(signingKey))
Dim oauthsignature As String = Convert.ToBase64String(hasher.ComputeHash(New ASCIIEncoding().GetBytes(finalBaseString)))
ServicePointManager.Expect100Continue = False
Dim wRequest As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
Dim authorizationHeaderParams As StringBuilder = New StringBuilder()
authorizationHeaderParams.Append("OAuth ")
authorizationHeaderParams.Append("oauth_nonce=" & """" + Uri.EscapeDataString(oauthnonce) & """,")
authorizationHeaderParams.Append("oauth_signature_method=" & """" + Uri.EscapeDataString(oauthsignaturemethod) & """,")
authorizationHeaderParams.Append("oauth_timestamp=" & """" + Uri.EscapeDataString(oauthtimestamp) & """,")
authorizationHeaderParams.Append("oauth_consumer_key=" & """" + Uri.EscapeDataString(oauthconsumerkey) & """,")
If Not String.IsNullOrEmpty(oauthtoken) Then authorizationHeaderParams.Append("oauth_token=" & """" + Uri.EscapeDataString(oauthtoken) & """,")
authorizationHeaderParams.Append("oauth_signature=" & """" + Uri.EscapeDataString(oauthsignature) & """,")
authorizationHeaderParams.Append("oauth_version=" & """" + Uri.EscapeDataString(oauthversion) & """")
wRequest.Headers.Add("Authorization", authorizationHeaderParams.ToString)
wRequest.Method = "GET"
wRequest.ContentType = "application/json"
wRequest.Accept = "application/json"
Try
Dim wResponse As WebResponse = wRequest.GetResponse()
Dim dataStream As Stream = wResponse.GetResponseStream()
Dim reader As StreamReader = New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
If responseFromServer = Nothing Then
TextBox1.Text = "No response from server"
Else
Dim json As String = responseFromServer
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
Dim output As String = ""
Dim successReq As Boolean = False
Dim avDom As String = ""
For Each item As JProperty In data
item.CreateReader()
output += "|-" & item.Name.ToString & " : " & item.Value.ToString & "-"
output += Environment.NewLine
Next
TextBox1.Text = output
End If
Catch ex As Exception
TextBox1.Text = ex.Message.ToString
End Try
Private Function EncodeCharacters(ByVal data As String) As String
If data.Contains("!") Then data = data.Replace("!", "%21")
If data.Contains("'") Then data = data.Replace("'", "%27")
If data.Contains("(") Then data = data.Replace("(", "%28")
If data.Contains(")") Then data = data.Replace(")", "%29")
If data.Contains("*") Then data = data.Replace("*", "%2A")
If data.Contains(",") Then data = data.Replace(",", "%2C")
Return data
End Function
This example is working

HTTPS - Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host

I am trying to access the below API Create method. I'm getting the following error when attempting to call webRequest1.GetRequestStream():
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host
Code:
Public Function OfferAffirmRequestURL(ByVal strHost As String, ByVal strClientId As String, ByVal strSecretKey As String, ByVal strApiPath As String) As String
Dim strOfferCommand As String = ""
Dim strHROBUrl As String = ""
Dim strHROBRequestURL As String = "https://" & strHost
Dim strErrorMessage As String
Dim strXMLString As String = "<?xml version=""1.0"" encoding=""UTF-8""?><Record><ReferenceID>44</ReferenceID><Template>New Offer</Template><RecordData><FormField><candidate_first_name>RBFName16</candidate_first_name><candidate_last_name>LName160</candidate_last_name><candidate_email>rbinteg160#affirmsoftware.com.au</candidate_email><candidate_mobile_no>0411111111</candidate_mobile_no><start_date>2014-07-16T00:00:00</start_date></FormField></RecordData></Record>"
Dim strTimeStamp As String = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")
Dim data As String = "clientId" & strClientId & "payload" & strXMLString & "timestamp" & strTimeStamp
Dim key As Byte() = StringToByteArray(strSecretKey)
Dim encrypt As HMACSHA1 = New HMACSHA1(key)
Dim dataBytes As Byte() = Encoding.ASCII.GetBytes(data)
Dim signatureBytes As Byte() = encrypt.ComputeHash(dataBytes)
Dim strSignature As String = Convert.ToBase64String(signatureBytes)
Dim strSignatureParam As String = Uri.EscapeDataString(strSignature)
strHROBUrl = strHROBRequestURL & strApiPath & "?clientId=" & strClientId & "&payload=" & strXMLString & "&timestamp=" & strTimeStamp & "&signature=" & strSignatureParam
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(strXMLString)
ServicePointManager.Expect100Continue = False
Dim webRequest1 As WebRequest = WebRequest.Create(strHROBUrl)
'Dim webRequest1 As HttpWebRequest = DirectCast(WebRequest.Create(strHROBUrl), HttpWebRequest)
webRequest1.Method = "POST"
webRequest1.ContentType = "text/xml"
webRequest1.ContentLength = byteArray.Length
webRequest1.Credentials = CredentialCache.DefaultCredentials
Try
Dim requestWriter As IO.Stream = webRequest1.GetRequestStream()
requestWriter.Write(byteArray, 0, byteArray.Length)
requestWriter.Close()
Dim response As WebResponse
response = webRequest1.GetResponse()
Dim responseReader As New IO.StreamReader(response.GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
strErrorMessage = responseData
responseReader.Close()
webRequest1.GetResponse().Close()
Catch ex As WebException
strErrorMessage = ex.InnerException.Message
End Try
Return strErrorMessage
End Function
The above method gets called in the button Click method shown below:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strCreateOfferURL As String = ""
strCreateOfferURL = OfferAffirmRequestURL("abc.xyz.com", "xyz", "4d8b7jpojpodf031e", "/api/record/createRecord.shtml")
Label1.Text = strCreateOfferURL
End Sub
Below link solved my issue.
Http post error: An existing connection was forcibly closed by the remote host
I made this change.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Google Drive Rest: convert does not work

I am using the G Drive REST endpoints (not .net client) to upload docx files through vb .net. My problem is that if even i declare the query parameter "convert" as true, the files are getting uploaded but they never auto-convert.
The first thing i do is to create a new file with POST and after that i upload the content with Put in the upload uri in a separate request.
it does not even work when i use the Google Playground to upload the docx files.
Public Shared Function UploadStream(fileStream As IO.Stream, filename As String, mimetype As String, target As String, accesstoken As String, Optional ConvertToGDoc As Boolean = False) As String
Try
Dim subject As String = ""
Dim doc As New Aspose.Words.Document
Dim docformat = Aspose.Words.FileFormatUtil.DetectFileFormat(fileStream) ' detect the format of the file Then 'check if the file is doc or docx
If docformat.LoadFormat = Aspose.Words.LoadFormat.Doc Or docformat.LoadFormat = Aspose.Words.LoadFormat.Docx Then 'check if the file is word document
doc = New Aspose.Words.Document(fileStream)
subject = doc.BuiltInDocumentProperties.Subject 'get the subject from the word file
If doc.BuiltInDocumentProperties.Subject = "" Then subject = "none"
Else
subject = "none" 'set the subject as none if the file is not word file
End If
Dim localmd5 = Files.MD5stream(fileStream)
Dim baseaddress = "https://www.googleapis.com/drive/v2/files?convert=" + ConvertToGDoc.ToString
Dim req = Net.HttpWebRequest.Create(baseaddress)
req.Method = "POST"
req.Headers.Add("Authorization", "Bearer " + System.Web.HttpUtility.UrlEncode(accesstoken))
req.ContentType = "application/json"
Dim writer = New Newtonsoft.Json.Linq.JTokenWriter()
writer.WriteStartObject()
writer.WritePropertyName("title")
writer.WriteValue(filename)
writer.WritePropertyName("parents")
writer.WriteStartArray()
writer.WriteRawValue("{'id':'" + target + "'}")
writer.WriteEndArray()
writer.WritePropertyName("properties")
writer.WriteStartArray()
writer.WriteRawValue("{'key':'Subject','value':'" + subject + "'},{'key':'MD5','value':'" + localmd5 + "'},{'key':'Author','value':''}")
writer.WriteEndArray()
writer.WriteEndObject()
Dim bodybytes = Text.Encoding.UTF8.GetBytes(writer.Token.ToString)
req.ContentLength = bodybytes.Length
Dim requestStream = req.GetRequestStream
requestStream.Write(bodybytes, 0, bodybytes.Length)
requestStream.Close()
Dim resp As System.Net.HttpWebResponse = req.GetResponse()
Dim response = New IO.StreamReader(resp.GetResponseStream, False).ReadToEnd
Dim json As Newtonsoft.Json.Linq.JObject
json = Newtonsoft.Json.Linq.JObject.Parse(response)
Dim fileId = json.SelectToken("id").ToString()
baseaddress = "https://www.googleapis.com/upload/drive/v2/files/" + fileId + "?uploadType=media&convert=" + ConvertToGDoc.ToString
req = Net.HttpWebRequest.Create(baseaddress)
req.Method = "Put"
req.Headers.Add("Authorization", "Bearer " + System.Web.HttpUtility.UrlEncode(accesstoken))
bodybytes = General.GetStreamAsByteArray(fileStream)
req.ContentLength = bodybytes.Length
req.ContentType = mimetype
requestStream = req.GetRequestStream
requestStream.Write(bodybytes, 0, bodybytes.Length)
requestStream.Close()
resp = req.GetResponse()
response = New IO.StreamReader(resp.GetResponseStream, False).ReadToEnd
Return fileId
Catch ex As Exception
Return Nothing
End Try
End Function
Shared Function GetStreamAsByteArray(ByVal stream As System.IO.Stream) As Byte()
Dim streamLength As Integer = Convert.ToInt32(stream.Length)
Dim fileData As Byte() = New Byte(streamLength) {}
stream.Position = 0
' Read the file into a byte array
stream.Read(fileData, 0, streamLength)
stream.Close()
ReDim Preserve fileData(fileData.Length - 2)
Return fileData
End Function
Public Shared Function MD5stream(ByVal File_stream As IO.Stream, Optional ByVal Seperator As String = Nothing) As String
Using MD5 As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim Hash() As Byte = MD5.ComputeHash(File_stream)
Return Replace(BitConverter.ToString(Hash), "-", Seperator)
End Using
End Function
Had anyone else the same problem?

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