How to POST a JSON to a specific url using VB.NET? - vb.net

I'm a newbie about web services in VB.NET. I'm making a desktop application that will talk to JIRA (http://www.atlassian.com/software/jira/). They provided a REST api that I decided to use. The first step is to login which they say that...
"To log in to JIRA, you need to POST a username and password in JSON format..."
{"username" : "admin", "password" : "admin"}
to this url...
https://addressgoeshere (we are using https)
Can someone provide me a sample code to do this so I can have a guide and a good start?

Here is the code to post json effectively. The variable res is able to give you the responce to your query
remember to import
System.Net
System.IO
System.text
by using
Imports
and then the import names
to bypass expired ssl certificate check this: http://blog.jameshiggs.com/2008/05/01/c-how-to-accept-an-invalid-ssl-certificate-programmatically/
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim response As String
Dim request As WebRequest
request = WebRequest.Create(uri)
request.ContentLength = jsonDataBytes.Length
request.ContentType = contentType
request.Method = method
Using requestStream = request.GetRequestStream
requestStream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
requestStream.Close()
Using responseStream = request.GetResponse.GetResponseStream
Using reader As New StreamReader(responseStream)
response = reader.ReadToEnd()
End Using
End Using
End Using
Return response
End Function
to use this function
Dim data = Encoding.UTF8.GetBytes(jsonSring)
Dim result_post = SendRequest(uri, data, "application/json", "POST")
--EDIT--
The linked page has expired by now. Here is a working archived copy:
https://web.archive.org/web/20110924191356/http://blog.jameshiggs.com/2008/05/01/c-how-to-accept-an-invalid-ssl-certificate-programmatically/

For 'The underlying connection was closed:' error include these 2 lines of code after the line ...WebRequest.Create(Url) -it should work
System.Net.ServicePointManager.UseNagleAlgorithm = False
System.Net.ServicePointManager.Expect100Continue = False

Related

RestSharp call to eBay oauth2 user token

I am trying to get eBay user tokens for my users using the identity api. I finally got it to work in Postman. Converted the call from Postman to a restsharp call from a vb.net test app. The Postman call works, the VB call returns "404 Not Found". Looked at the two calls using Fiddler. The only difference I can see is that the Postman call goes to:
"POST https://api.sandbox.ebay.com/identity/v1/oauth2/token";
and the VB app call goes to
"POST https://api.sandbox.ebay.com/identity/v1/oauth2/token/1"
It would appear that somewhere the VB app is appending "/1" to the api url. Not sure where this is occurring as I can step through the code as it executes and don't see it.
Is there a property in RestSharp that might cause this value to be appended?
EDIT added code. This code is supposed to return a user token and refresh token from eBay. It is taken pretty much from Postman with mods to work with the latest version.
Async Sub RSGetCode(sCode As String)
Dim client As RestClient = New RestClient("https://api.sandbox.ebay.com/identity/v1/oauth2/token")
Dim request As RestRequest = New RestRequest(Method.Post)
sCode = WebUtility.UrlDecode(sCode)
With request
.AddHeader("Content-Type", "application/x-www-form-urlencoded")
.AddHeader("Authorization", "Basic TXVycGh5c0MtNzYxNy00ZGRmLTk5N2ItOD..........................")
.AddParameter("grant_type", "authorization_code")
.AddParameter("code", sCode)
.AddParameter("redirect_uri", "Murphys_Creativ-Mu...........")
.AddParameter("Scope", "https://api.ebay.com/oauth/api_scope/sell.inventory")
End With
Dim responce = Await client.PostAsync(request)
'Dim responce = Await client.ExecuteAsync(request)
Dim sR As String = responce.Content
End Sub```
I got it to work by slightly reformating the code. See below.
Async Sub PostRestCode(sCode As String)
Dim client As RestClient = New RestClient("https://api.sandbox.ebay.com")
Dim request As RestRequest = New RestRequest("identity/v1/oauth2/token", Method.Post)
With request
.AddHeader("Content-Type", "application/x-www-form-urlencoded")
.AddHeader("Authorization", "Basic TXVycGh5c0MtNzYxNy00ZGRmLTk5N2ItODc2OGMzZWZkYT..............................")
.AddParameter("grant_type", "authorization_code")
.AddParameter("code", sCode) '"v^1.1#i^1#I^3#p^3#f^0#r^1#t^Ul41Xzg6NEN.......................................")
.AddParameter("redirect_uri", "Murphys_Creativ-Mu......................")
.AddParameter("Scope", "https://api.ebay.com/oauth/api_scope/sell.inventory")
End With
Dim responce = Await client.PostAsync(request)
'Dim responce = Await client.ExecuteAsync(request)
Dim sR As String = responce.Content
End Sub

How to send encrypted email through sendgrid using tls and vb.net API post call?

I created a console program on visual basic asp.net that sends a generated email through a post API call. I was successful in sending an email to any recipient email using a godaddy domain through sendgrid. On this domain godaddy, I set up a proofpoint encryption attachment that should create encrypted emails through a trigger of putting "[encrypt]" in the subject line. However, it did not trigger because for the encryption to be automatically attached to the email it has to pass through the office 365 server. Since I am using sendgrid according to the workflow it doesn't go through outlook whatsoever:
https://sendgrid.com/docs/ui/sending-email/email-flow/
I have been doing research and I see send sendgrid supports end-to-end encryption with TLS. However, I cannot find anywhere how to establish this encryption with sendgrid and visual basic API calls. This program is for a medical diagnostic company, who will be sending patient information via email, to maintain HIPPA compliance the emails must be encrypted in some way. Here is the code:
Private Sub SendEmail(PARAMETERS_FOR_AUTOMATING_EMAIL)
Try
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12
Dim uri As String = "https://api.sendgrid.com/v3/mail/send"
Dim Request As WebRequest = WebRequest.CreateHttp(uri)
Request.Method = "POST"
Request.PreAuthenticate = True
Request.Headers.Add("Authorization", "Bearer API_KEY")
Dim json_data As String = "{""personalizations"": [{""To"": [{""email"": ""TO_EMAIL""}]}],""from"": {""email"": ""FROM_EMAIL""},""subject"":""[Encrypt]This is a automated report"",""content"": [{""type"": ""text/html"",""value"": ""Hello!,<br>Please find attachment.""}], ""attachments"": [{""content"": ""File_translated_to_64_encoded"", ""type"": ""EXCEL_MIME"", ""filename"": ""FILE_NAME_FOR_ATTACHMENT""}]}}"
Request.ContentType = "application/json"
Dim json_bytes() As Byte = Encoding.UTF8.GetBytes(json_data)
Request.ContentLength = json_bytes.Length
Using requeststream = Request.GetRequestStream
requeststream.Write(json_bytes, 0, json_bytes.Length)
End Using
Dim responsecontent As String = Nothing
Using Response = DirectCast(Request.GetResponse, HttpWebResponse),
responseStream = Response.GetResponseStream()
Using reader = New StreamReader(responseStream)
responsecontent = reader.ReadToEnd()
End Using
End Using
Catch ex As Exception
ErrLog(ex, currentLocID)
End Try
End Sub
If you guys have any ideas to give me a solution please share! thank you in advance.

Visual Basic Access Token Youtube API Returning Error 400

So, I'm trying to make a program that will upload videos for me so I don't have to take so much time, and I've come up with the following code:
Imports System
Imports System.Net
Imports System.IO
Module Module1
Sub Main()
Dim bytearray As String = "code=4/5tC9qk5APvWf_05GJRG-Ws5Ph4B1xXMZd0gw4iZEB50&
client_id=349673303318-cp0upvjfcijukhnloppnpl5v57qkrr53.apps.googleusercontent.com&
client_secret=s7gStNsZWua50Hlpot2XfSga&
redirect_uri=https://localhost/oauth2callback&
grant_type=authorization_code"
Dim request As WebRequest = WebRequest.Create("https://accounts.google.com/o/oauth2/token")
request.Credentials = CredentialCache.DefaultCredentials
request.Method = "POST"
request.ContentLength = bytearray.Length
request.ContentType = "application/x-www-form-urlencoded"
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write((Text.Encoding.UTF8.GetBytes(bytearray)), 0, bytearray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
My.Computer.Clipboard.SetText(Convert.ToString(response.GetResponseStream))
response.Close()
End Sub
End Module
This is in Visual Basic.
The problem is that it returns an Error 400 (Bad Request) from the server when I send the request.
Kindly check additional error details then you may refer to YouTube - Errors to help you troubleshoot encountered error.
Additionally, comments in this SO post - Youtube Api : Error 400 Bad Request while uploading videos might also help.

Anonymous HTTP Web Request

I created http request application to test my web site qulatiy (see below).
Dim Request As HttpWebRequest = WebRequest.Create(webAddress)
Dim Response As HttpWebResponse = Request.GetResponse()
Request.Method = "Get"
Dim Reader As New StreamReader(Response.GetResponseStream)
Dim Html As String = Reader.ReadToEnd()
In this case, I would like to create anonymous request without catching the response. How can I do that?
To do so, u have to get a little low level , working with sockets
TcpCient in this case
Sample code
Imports System.Net.Sockets
Module Module1
Sub Main()
Dim tcpcli = New TcpClient()
tcpcli.Connect("google.co.in", 80)
Dim stream As NetworkStream = tcpcli.GetStream()
Dim reqdata As String = String.Format("GET / HTTP/1.1{0}Host: www.google.co.in{0}Connection: Close{0}{0}", vbCrLf)
Dim reqbytes() As Byte = Text.Encoding.ASCII.GetBytes(reqdata)
stream.Write(reqbytes, 0, reqbytes.Length)
stream.Close()
stream.Dispose()
tcpcli.Close()
End Sub
End Module
Network capture via wireshark (no response received)
You can make a web request anonymously by using ProxySharp. It basically makes the web request behind a random vpn each time. This makes it look like the request is coming from a different IP address on each request.

How to use HttpWebRequest to download file

Trying to download file in code.
Current code:
Dim uri As New UriBuilder
uri.UserName = "xxx"
uri.Password = "xxx"
uri.Host = "xxx"
uri.Path = "xxx.aspx?q=65"
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(uri.Uri), HttpWebRequest)
request.AllowAutoRedirect = True
request = DirectCast(WebRequest.Create(DownloadUrlIn), HttpWebRequest)
request.Timeout = 10000
'request.AllowWriteStreamBuffering = True
Dim response As HttpWebResponse = Nothing
response = DirectCast(request.GetResponse(), HttpWebResponse)
Dim s As Stream = response.GetResponseStream()
'Write to disk
Dim fs As New FileStream("c:\xxx.pdf", FileMode.Create)
Dim read As Byte() = New Byte(255) {}
Dim count As Integer = s.Read(read, 0, read.Length)
While count > 0
fs.Write(read, 0, count)
count = s.Read(read, 0, read.Length)
End While
'Close everything
fs.Close()
s.Close()
response.Close()
Running this code and checking the response.ResponseUri indicates im being redirected back to the login page and not to the pdf file.
For some reason its not authorising access what could I be missing as Im sending the user name and password in the uri? Thanks for your help
You don't need all of that code to download a file from the net
just use the WebClient class and its DownloadFile method
you should check and see if the site requires cookies (most do), i'd use a packet analyzer and run your code and see exactly what the server is returning. use fiddler or http analyzer to log packets
With UWP, this has become a more pertinent question as UWP does not have a WebClient. The correct answer to this question is if you are being re-directed to the login page, then there must be an issue with your credentials OR the setting (or lack of) header for the HttpWebRequest.
According to Microsoft, the request for downloading is sent with the call to GetResponse() on the HttpWebRequest, therefore the downloaded file SHOULD be in the stream in the response (returned by the GetResponse() call mentioned above).