Creating webrequest POST for Twitter API using VB.NET - vb.net

There are quite a few Twitter API related posts, but none seem to answer my questions directly.
I know how to send an HttpWebRequest as POST.
I am fairly sure I need to send the webrequest to: "https://api.twitter.com/1/statuses/update.json" (not totally clear)
I know there are many libraries out there that all you have to do is pass your consumer keys and token keys. However, I need to create some very short code, in a function, that simple posts a hard coded string to Twitter. When I get this working that hard coded string will be replaced by variable.
I've no need to status updates or any kind of information from Twitter. Just POST "Hello World!" to start with, and I can go from there.
I am forced to use VB.NET. I am using Visual Studio Web Developer 2010.
Now, that all said, I have looked at Nikolas Tarzia's VB.NET port of C-Sharp code here:
http://oauth.googlecode.com/svn/code/vbnet/oAuth.vb
I can see roughly what the functions do by looking at them, but have no idea which ones I need to call to create a webresponse and send to Twitter! Also I believe this code contains more than I need. If I just want to create a POST, then likely I only need to hash function and the nonce function and my tokens and keys. Is that right? If so, could someone please help me narrow this down? In the process helping me understand a bit better what properly formed webrequest needs to be sent to Twitter to make a quick Tweet?
Thanks,
Will
PS - I finally put together some code, based on looking at OAuth documentation, a neat little code example on using POST request in VB, and the Twitter Developer area OAuth tool to generate some Base String for the request. Unfortunately while it compiles and runs okay, I am not getting a tweet. Could someone have a look at the code and see if they can spot any glaring issues? Obviously I replaced my tokens and consumer keys with "xxxxx". All I want for Christmas is to run this code and make a quick Tweet on my Twitter account! ;)
Public Shared Function Tweet(strText As String) As Boolean
Dim boolResult As Boolean = False
Dim urlAddress As Uri = New Uri("https://api.twitter.com/1/statuses/update.json")
Dim strData As StringBuilder
Dim byteData() As Byte
Dim postStream As Stream = Nothing
Dim strConsumerKey As String = "xxxxxx"
Dim strConsumerSecret As String = "xxxxxx"
Dim strAccessToken As String = "xxxxxx"
Dim strAccessTokenSecret As String = "xxxxxx"
Dim objRequest As HttpWebRequest
Dim objResponse As HttpWebResponse = Nothing
Dim objReader As StreamReader
Dim objHeader As HttpRequestHeader = HttpRequestHeader.Authorization
Try
objRequest = DirectCast(WebRequest.Create(urlAddress), HttpWebRequest)
objRequest.Method = "POST"
objRequest.ContentType = "application/x-www-form-urlencoded"
strData = New StringBuilder()
strData.Append("&Hello_World%2521%3D%26oauth_consumer_key%3D" + strConsumerKey + "%26oauth_nonce%3Dda6bb8ce7e48547692f4854833afa680%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1329746260%26oauth_token%3D" + strAccessToken + "%26oauth_version%3D1.0")
objRequest.Headers.Add(objHeader, "Authorization: OAuth oauth_consumer_key=""xxxx"", oauth_nonce=""da6bb8ce7e48547692f4854833afa680"", oauth_signature=""xxxx"", oauth_signature_method=""HMAC-SHA1"", oauth_timestamp=""1329750426"", oauth_token=""xxxx"", oauth_version=""1.0""")
' Create a byte array of the data we want to send
byteData = UTF8Encoding.UTF8.GetBytes(strData.ToString())
' Set the content length in the request headers
objRequest.ContentLength = byteData.Length
Try
postStream = objRequest.GetRequestStream()
postStream.Write(byteData, 0, byteData.Length)
Finally
If Not postStream Is Nothing Then postStream.Close()
End Try
boolResult = True
Catch ex As Exception
boolResult = False
HttpContext.Current.Session.Add("Error", ex.ToString())
End Try
Try
' Get response
objResponse = DirectCast(objRequest.GetResponse(), HttpWebResponse)
' Get the response stream into a reader
objReader = New StreamReader(objResponse.GetResponseStream())
' Console application output
Console.WriteLine(objReader.ReadToEnd())
Finally
If Not objResponse Is Nothing Then objResponse.Close()
End Try
Return boolResult
End Function

I´ve made this class to post in twitter using API1.1.
It expects the oauth token, oauth token secret, oauth "consumer" key (this means API key) and oauth consumer secret (this means API secret) in the constructor. If you want to post in your own account, the four values will be in the API keys tab of your application in https://apps.twitter.com/. If you want to post on your visitors account you'll have to create some extra code to redirect them to twitter for login and get the access token.
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Text
Imports System.Security.Cryptography
Imports System.Net
Imports System.IO
Public Class SBTwitter
Private oauth_token As String
Private oauth_token_secret As String
Private oauth_consumer_key As String
Private oauth_consumer_secret As String
Public Sub New(ByVal APIKey As String, ByVal APISecret As String, ByVal oauthToken As String, ByVal oauthTokenSecret As String)
oauth_token = oauthToken
oauth_token_secret = oauthTokenSecret
oauth_consumer_key = APIKey
oauth_consumer_secret = APISecret
End Sub
Public Function PostInTwitter(ByVal post As String) As String
Try
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 = "https://api.twitter.com/1.1/statuses/update.json"
Dim status = post
Dim baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" & "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}"
Dim baseString = String.Format(baseFormat, oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_token, _
oauth_version, Uri.EscapeDataString(status))
baseString = String.Concat("POST&", 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))
Dim postBody = "status=" & Uri.EscapeDataString(status)
ServicePointManager.Expect100Continue = False
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(resource_url), HttpWebRequest)
request.Headers.Add("Authorization", authHeader)
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
Using stream As Stream = request.GetRequestStream()
Dim content As Byte() = ASCIIEncoding.ASCII.GetBytes(postBody)
stream.Write(content, 0, content.Length)
End Using
Dim response As WebResponse = request.GetResponse()
Return response.ToString
Catch ex As Exception
Return ex.Message
End Try
End Function
End Class

Related

Oauth 2.0 SMTP send email with EASendEmail VB

Following the changes, I try to connect and send mails via EAGetMail/EASendMail.
The connection is good, I have good access to the token and also to my mailbox.
However, when I want to send an email via "smtp.office365.com" I get an error: 535 5.7.3 Authentication unsuccessful.
I do not understand where the error can come from, I take the same token as when connecting to the mailbox.
Below is just the code to send emails, I have a token and it works perfectly to connect to my email
If someone has a project that works with smtp and Oauth 2.0 (without using a browser)...
Module Module1
Sub Main(ByVal args As String())
Try
RetrieveEmail()
Catch ep As Exception
Console.WriteLine(ep.ToString())
End Try
Console.ReadKey()
End Sub
Function _generateFileName(ByVal sequence As Integer) As String
Dim currentDateTime As DateTime = DateTime.Now
Return String.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", New CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence)
End Function
Function _postString(ByVal uri As String, ByVal requestData As String) As String
Dim httpRequest As HttpWebRequest = TryCast(WebRequest.Create(uri), HttpWebRequest)
httpRequest.Method = "POST"
httpRequest.ContentType = "application/x-www-form-urlencoded"
Using requestStream As Stream = httpRequest.GetRequestStream()
Dim requestBuffer As Byte() = Encoding.UTF8.GetBytes(requestData)
requestStream.Write(requestBuffer, 0, requestBuffer.Length)
requestStream.Close()
End Using
Try
Dim httpResponse As HttpWebResponse = TryCast(httpRequest.GetResponse(), HttpWebResponse)
Using reader As New StreamReader(httpResponse.GetResponseStream())
Dim responseText = reader.ReadToEnd()
Return responseText
End Using
Catch ex As WebException
If ex.Status = WebExceptionStatus.ProtocolError Then
Dim response = TryCast(ex.Response, HttpWebResponse)
If response IsNot Nothing Then
Console.WriteLine("HTTP: " & response.StatusCode)
' reads response body
Using reader As StreamReader = New StreamReader(response.GetResponseStream())
Dim responseText As String = reader.ReadToEnd()
Console.WriteLine(responseText)
End Using
End If
End If
Throw ex
End Try
End Function
Public Sub RetrieveEmail()
Try
Dim client_id As String = "XXXXXXXXXXXXXXXXXXXX"
Dim client_secret As String = "XXXXXXXXXXXXXXXXXXXXXXXXX"
' If your application is not created by Office365 administrator,
' please use Office365 directory tenant id, you should ask Offic365 administrator to send it to you.
' Office365 administrator can query tenant id in https://portal.azure.com/ - Azure Active Directory.
Dim tenant As String = "XXXXXXXXXXXXXXXXXX"
Dim requestData As String = String.Format("client_id={0}&client_secret={1}&scope=https://outlook.office365.com/.default&grant_type=client_credentials",
client_id, client_secret)
Dim tokenUri As String = String.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", tenant)
Dim responseText As String = _postString(tokenUri, requestData)
Dim parser As EASendMail.OAuthResponseParser = New EASendMail.OAuthResponseParser()
parser.Load(responseText)
Dim officeUser As String = "tma#XXXX.fr"
Dim oServerSend As SmtpServer = New SmtpServer("smtp.office365.com")
oServerSend.ConnectType = SmtpConnectType.ConnectSSLAuto
oServerSend.Port = 587
oServerSend.AuthType = SmtpAuthType.XOAUTH2
oServerSend.User = officeUser
oServerSend.Password = parser.AccessToken
Dim oMailSend As SmtpMail = New SmtpMail("TryIt")
oMailSend.From = "tma#XXX.fr"
' Please change recipient address to yours for test
oMailSend.[To] = "XXXXXXXXXXX"
oMailSend.Subject = "test email from Hotmail account with OAUTH 2"
oMailSend.TextBody = "this is a test email sent from VB.NET project with Hotmail."
Console.WriteLine("start to send email using OAUTH 2.0 ...")
Dim oSmtp As SmtpClient = New SmtpClient()
oSmtp.SendMail(oServerSend, oMailSend)
' Quit and expunge emails marked as deleted from server.
Console.WriteLine("Completed!")
Catch ep As Exception
Console.WriteLine(ep.ToString())
End Try
End Sub
End Module

HTTP POST .NET aspx.vb doesn't work using Class Library, works with Windows Forms Apps

I the code below works fine with using VS 2019 and selecting Windows Forms Applications from the project properties. When I try to use the same code though in a "Class Library" for Web Forms, it doesn't work.
Target framework is .NET Framework 4.7.2 (i have to stay within .NET 4.0 for other references)
The host server requires me to login (username/password) via a pop-up when URL is entered on a web browser. This is why you see below request.Credentials being used. As far as I know, the host system is using TLS 1.2 as well.
The error shows when it hits
Dim dataStream As Stream = request.GetRequestStream() 'Get the request stream.
But the HTTP/S POST also doesn't work, but doesn't error out either.
Could it be a bug with built in IIS Express (Google Chrome)? I tried IE and Edge, same thing.
Imports System.IO
Imports System.Net
Imports System.Text
Public Class POST_ASN
Inherits System.Web.UI.Page
'Protected Sub Page_Load(ByVal sender As Object, ByVal As Examples.System.EventArgs) Handles Me.Load
'End Sub
Public Shared Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim url As String = "https://myurl.somehost.com/invoke/HTTPConnector.Mailbox/post"
Dim username As String = "user123"
Dim password As String = "pass123"
Dim networkCredential As New NetworkCredential(username, password)
Dim postData As String = ""
' Create a request using a URL that can receive a post.
Dim Request As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
Request.Method = "POST"
request.PreAuthenticate = True
request.Credentials = networkCredential
' Create POST data and convert it to a byte array.
postData = "EDI data string here ASCII"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentType = "application/octet-stream" ' Set the ContentType property of the WebRequest.
request.ContentLength = byteArray.Length ' Set the ContentLength property of the WebRequest.
'Get the request stream.
Dim dataStream As Stream = request.GetRequestStream()
'Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length)
' Close the Stream object
dataStream.Close()
' Assign the response object of 'WebRequest' to a 'WebResponse' variable.
Dim response As WebResponse = request.GetResponse()
' Get the stream containing content returned by the server.
Dim trackingID As String
Using dataStream1 As Stream = response.GetResponseStream()
'Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream1)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
trackingID = Mid(responseFromServer, 65, 10)
' Display the content.
MsgBox("Tracking ID: " & trackingID)
End Using
' Clean up the response.
response.Close()
End Sub
End Class
I also read posts about setting ServicePointManager.SecuirtyProtocol, none of these worked, and i tried difference scenarios. According to MS, using .NET 4.7, TLS1.2 is already invoked.
'ServicePointManager.Expect100Continue = True
'ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)
'ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
'ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
'ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls 'Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls12
The purpose of all this was to migrate off my Excel VBA solution. This code below works fine, so if anyone knows how to take this and convert it to .NET Framework Class Library VB.aspx web page, please help.
'Create HTTP connection
Set xmlhttp = CreateObject("MSXML2.XMLHTTP.6.0")
xmlhttp.Open "POST", strURL, False, UploadUser, UploadPass 'Sync request
xmlhttp.Send sData
strValue = xmlhttp.responsetext
Set xmlhttp = Nothing
trackingID = Mid(strValue, 65, 10)

400 bad request when querying microsoft graph with http post

I've been doing some testing with Microsoft Graph and I seem to have hit a brick wall; Wondering if anyone can give me a steer in the right direction.
The following code is from my test app (vb)...
Imports System.Net
Imports System.Text
Imports System.IO
Imports Newtonsoft.Json.Linq
Class MainWindow
Public Shared graph_url As String = "https://graph.microsoft.com/v1.0/"
Public Shared br As String = ControlChars.NewLine
Dim myscope As String = "https://graph.microsoft.com/.default"
Dim mysecret As String = "zzx...BX-"
Dim mytenantid As String = "7aa6d...d409199"
Dim myclientid As String = "4e37...5a59"
Dim myuri As String = "https://login.microsoftonline.com/" & mytenantid & "/oauth2/v2.0/token"
Dim mytoken As String = ""
Public Function HTTP_Post(ByVal url As String, ByVal postdata As String)
Try
Dim encoding As New UTF8Encoding
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
postReq.Headers.Add("Authorization", "Bearer " & mytoken)
postReq.Method = "POST"
postReq.PreAuthenticate = True
Dim postreqstream As Stream = postReq.GetRequestStream()
If Not postdata = Nothing Then
Dim byteData As Byte() = encoding.GetBytes(postdata)
postreqstream.Write(byteData, 0, byteData.Length)
End If
postreqstream.Close()
request_header.Text = postReq.Headers.ToString
Dim postresponse As HttpWebResponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
Dim response As String = postreqreader.ReadToEnd
Return (response)
Catch ex As Exception
user_results.Text = ex.Message.ToString
End Try
End Function
Public Function GetNewToken()
Console.WriteLine(myuri)
Dim post_data As String = "client_id=" & myclientid & "&client_secret=" & mysecret & "&scope=" & myscope & "&grant_type=client_credentials"
Dim token As String = HTTP_Post(myuri, post_data)
get_result.Text = JObject.Parse(token).SelectToken("access_token")
mytoken = JObject.Parse(token).SelectToken("access_token")
End Function
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
GetNewToken()
End Sub
Private Sub usrget_Copy_Click(sender As Object, e As RoutedEventArgs) Handles usrget_Copy.Click
Dim url As String = "https://graph.microsoft.com/v1.0/users/*{myUPN}*"
Dim post_data As String = Nothing
Dim return_data As String = HTTP_Post(url, post_data)
req_url.Text = url
End Sub
End Class
The GetNewToken() function works fine and I retrive a valid token without an issue.
When i try and use that token to query a user, i get 400 Bad request - no additional info as such; just that.
I've examined the headers of my POST request and tried it several different ways, but cannot seem to overcome this; As far as i can tell my request is formatted as specified in the documentation for Microsoft Graph.
Have also googled the hell out of this to see if there was something obvious or simple I have overlooked; I've seen a few posts on this topic where people suggested setting the Authorization header before anything else - I tried that and it made no difference.
A few people also suggected setting the Accept to 'application/json'; I also tried that and it made no difference.
I've outputted some of the details to the gui and grabbed a screenshot so you can see what I'm seeing...
Interestingly, If i try the 'Query users' before i grab a token, I get a 401 unauthorized which would suggest that the request itself is working correctly.
As i mentioned, this is a testing app whilst I get some functionality working (some data obscured for obvious reasons); I'm not concerned about the tidyness of code or anything like that at this point.
If anyone is able to help it would be very much appriciated.
Thanks in advance.

VB.NET - Salesforce POST Request returns 400 Bad Request Error

NOTE: I've never written vb.net code before this. I've googled for a solution but did not find anything that worked.
I'm trying to get access token from Salesforce. Below code worked just yesterday. And I have no idea why it is not working today. I've tried adding content-type as application/x-www-form-urlencoded but it did not work either. When I use curl I'm able to get access token. Also I'm able to get access token using advanced rest client in google chrome. Any ideas why it is returning 400 Bad Request unknown error retry your request?
Imports System.Collections.Specialized
Imports System.Net
Imports System.Text
Module Module1
Sub Main()
Dim clientId As String = "clientId"
Dim clientSecret As String = "clientSecret"
Dim redirectUri As String = "https://test.salesforce.com"
Dim environment As String = "https://test.salesforce.com"
Dim tokenUrl As String = ""
Dim username As String = "username#salesforce.com"
Dim password As String = "passwordtoken"
Dim accessToken As String = ""
Dim instanceUrl As String = ""
Console.WriteLine("Getting a token")
tokenUrl = environment + "/services/oauth2/token"
Dim request As WebRequest = WebRequest.Create(tokenUrl)
Dim values As NameValueCollection = New NameValueCollection()
values.Add("grant_type", "password")
values.Add("client_id", clientId)
values.Add("client_secret", clientSecret)
values.Add("redirect_uri", redirectUri)
values.Add("username", username)
values.Add("password", password)
request.Method = "POST"
Try
Dim client = New WebClient()
Dim responseBytes As Byte() = client.UploadValues(tokenUrl, "POST", values)
Dim response As String = Encoding.UTF8.GetString(responseBytes)
Console.WriteLine(response)
Console.ReadKey()
Catch ex As Exception
Console.WriteLine(ex.Message)
Console.WriteLine("Press any key to close")
Console.ReadKey()
End Try
End Sub
End Module
Well, appearently problem was about TLS version mismatch. All Salesforce sandboxes refuse TLS 1.0 connections. Our vb.net test code was using TLS 1.0 thus returning an error. It would be great if Salesforce would return better error code.
All I needed to do was add a line of code on top of the code block:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11

Google OAuth Token error - 400 Bad Request

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