Visual Basic Access Token Youtube API Returning Error 400 - vb.net

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.

Related

Submit Form POST using VB .NET

I have searched a solution to my problem extensively, and while I found answers that seemed to have worked for others, I am just having a real hard time figuring this out. But I feel I am very close.
I am trying to make an Rest API call to an online application called Zoho Creator. I am trying to implement the Add Record call. The example they give is using an HTML form with a submit button. But I need to Add Records from a VB .NET desktop application. I have tried both WebClient and WebRequest, but I am unsuccessful in those attempts. But I have been successful using these methods with other API calls and other APIs, it's just this Add Records one that is giving me trouble.
One of the required parameters is an authtoken, which for security reasons I replaced with "xxxxxxxxxx". Here is an html form that I created and when I use it, it created the record successfully thru the API, it's just adding a single record with the single field value for "TicketID".
<!DOCTYPE html>
<html>
<body>
<form method="POST" action="https://creator.zoho.com/api/max1stdirectcom/xml/service-orders/form/Ticket_form/record/add">
<input type="hidden" name="authtoken" value="xxxxxxxxxx"/>
<input type="hidden" name="scope" id="scope" value="creatorapi"/>
<input type="text" name="TicketID" value="123"/>
<input type="submit" value="Add Record"/>
</form>
<body>
So, the above works perfectly fine. now, here is my VB .NET code trying to replicate the same result using WebRequest:
Protected Sub PostTo(sTicketID As String)
Dim url As String = "https://creator.zoho.com/api/max1stdirectcom/xml/service-orders/form/Ticket_form/record/add"
Dim request As WebRequest = WebRequest.Create(url)
request.Method = "POST"
' Create POST data and convert it to a byte array.
Dim postData As String = "?authtoken=" & "xxxxxxxxxx" & "?scope=creatorapi" & "?TicketID=" & sTicketID
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
' Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded"
' Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length
' 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()
' Get the response.
Dim response As WebResponse = request.GetResponse()
' Display the status.
Debug.WriteLine(CType(response, HttpWebResponse).StatusDescription)
' Get the stream containing content returned by the server.
dataStream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
' Display the content.
Debug.WriteLine(responseFromServer)
' Clean up the streams.
reader.Close()
dataStream.Close()
response.Close()
End Sub
The response I get from the call using the above VB .Net code is:
<response>
<errorlist>
<error>
<code>2899</code>
<message><![CDATA[Permission Denied To Add Record(s).]]></message>
</error>
</errorlist>
</response>
So it is obviously making good communication with the API on some level. I am using the correct AuthToken, so not sure why it is rejecting the adding of the record. I am passing the same exact "credentials" as the basic form POST, but getting different result.
Any recommendations for me to try?
Below is a working code in VB .Net
Please check and add the missing implementation in your code.
Private Sub HTTPRestPOST (ByVal JsonInputStr As String, ByVal POSTUri As String)
'Make a request to the POST URI
Dim RestPOSTRequest As HttpWebRequest = HttpWebRequest.Create(POSTUri)
'Convert the JSON Input to Bytes through UTF8 Encoding
Dim JsonEncoding As New UTF8Encoding()
Dim JsonBytes As Byte() = JsonEncoding.GetBytes(JsonInputStr)
'Setting the request parameters
RestPOSTRequest.Method = "POST"
RestPOSTRequest.ContentType = "application/json"
RestPOSTRequest.ContentLength = JsonBytes.Length
'Add any other Headers for the URI
RestPOSTRequest.Headers.Add("username", "kalyan_nakka")
RestPOSTRequest.Headers.Add("password", "********")
RestPOSTRequest.Headers.Add("urikey", "MAIJHDAS54ADAJQA35IJHA784R98AJN")
'Create the Input Stream for the URI
Using RestPOSTRequestStream As Stream = RestPOSTRequest.GetRequestStream()
'Write the Input JSON data into the Stream
RestPOSTRequestStream.Write(JsonBytes, 0, JsonBytes.Length)
'Response from the URI
Dim RestPOSTResponse = RestPOSTRequest.GetResponse()
'Create Stream for the response
Using RestPOSTResponseStream As Stream = RestPOSTResponse .GetResponseStream()
'Create a Reader for the Response Stream
Using RestPOSTResponseStreamReader As New StreamReader(RestPOSTResponseStream)
Dim ResponseData = RestPOSTResponseStreamReader.ReadToEnd()
'Later utilize "ResponseData" variable as per your requirement
'Close the Reader
RestPOSTResponseStreamReader.Close()
End Using
RestPOSTResponseStream.Close()
End Using
RestPOSTRequestStream.Close()
End Using
End Sub

How to catch the post data sent to the redirect URL (VB 2010)

I am trying to login to one web page via my Windows Form application (VB 2010) and get some response, but I don't know how to do it.
The server service is described here:
https://api.developer.betfair.com/services/webapps/docs/display/1smk3cen4v3lu3yomq5qye0ni/Interactive+Login+from+a+Desktop+Application
On beginning I tried to insert WebBrowser Control to my form, but I read many articles, also here, that using BeforeNavigate2 event is an old way.
I would like to do this:
Send HTTP request to webserver including username and password
Catch the post data sent to the redirect URL
Read the POST request body an get loginStatus and productToken (SSOID)
This is my code:
Private Sub getPOST()
' Create a request for the URL
Dim request As WebRequest = _
WebRequest.Create("https://identitysso.betfair.com/view/login?product=82&url=https://www.betfair.com&username=abc&password=abc")
request.Method = "POST"
' Get the response
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
' Get the stream containing content returned by the server.
Dim dataStream As Stream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
' Display the content.
RichTextBox1.Text = responseFromServer
' Cleanup the streams and the response.
reader.Close()
dataStream.Close()
response.Close()
End Sub
But this code returns HTML code of page where are not loginStatus and SSOID.
I examined this page and discovered there are a few problems with your code:
First you are posting to the wrong URL because the www.betfair.com/view/login form has action="/api/login", not "/view/login". Second, you are passing your username/password in the QueryString rather than in POSTDATA... this form uses method=post. Third, you are not passing all required fields. This code snippet should remedy these described problems, as well as answer your question about obtaining the redirect URL:
Sub TestWebClient()
' Create a request for the URL
' You were using the wrong URL & passing the values improperly
' I also changed this to HttpWebRequest, used to be WebRequest.
Dim request As HttpWebRequest = WebRequest.Create("https://identitysso.betfair.com/api/login") '
request.Method = "POST"
' New code added
request.ContentType = "application/x-www-form-urlencoded"
' New code added, this prevents the following of the 302 redirect in the Location header
request.AllowAutoRedirect = False
' New code added, this sends the values as POSTDATA, which is contained inside the HTTP POST request rather than in the URL
Using writer As New StreamWriter(request.GetRequestStream)
writer.Write("username=abc")
writer.Write("&password=abc")
writer.Write("&login=true")
writer.Write("&redirectMethod=POST")
writer.Write("&product=82")
writer.Write("&url=https://www.betfair.com/")
writer.Write("&ioBlackBox=")
End Using
' Get the response
' This will print the Location header (aka "Redirect URL") on the screen for you
' Make decisions as needed.
Dim response As HttpWebResponse = request.GetResponse()
Console.WriteLine("HTTP RESPONSE HEADERS:")
For Each item In response.Headers
Console.WriteLine(item & "=" & response.Headers(item))
Next
Console.ReadLine()
End Sub

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 POST a JSON to a specific url using 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

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).