I am trying to access a page where I need to log into the website and pass a a list of parameters. I appear to be able to log into the site (if I change the log in details I get a 401 unauthorised error) but then I get a 400 bad request error. The code is a bit hashed together so I know something is wrong but don't know where.
EDITED CODE
Public Sub TestConn()
Dim customeremailaddress As String = HttpUtility.UrlEncode("r.test#test.com")
Dim customername As String = HttpUtility.UrlEncode("Ryan")
Dim referenceid As String = HttpUtility.UrlEncode("ordertest123")
Dim languagecode As String = HttpUtility.UrlEncode("1043")
Dim expirydays As String = HttpUtility.UrlEncode("30")
Dim UserName As String = "testusername"
Dim password As String = "testpassword"
Dim siteCredentials As New NetworkCredential(UserName, password)
Dim URLAuth As String = "http://service.someurl.com/process.xml"
Dim postString As String = String.Format("customeremailaddress={0}&customername={1}&referenceid={2}&languagecode={3}&expirydays={4}", customeremailaddress, customername, referenceid, languagecode, expirydays)
Dim postBytes As Byte() = Encoding.UTF8.GetBytes(postString)
Const contentType As String = "application/x-www-form-urlencoded"
System.Net.ServicePointManager.Expect100Continue = False
Dim cookies As New CookieContainer()
Dim webRequest__1 As HttpWebRequest = TryCast(WebRequest.Create(URLAuth), HttpWebRequest)
webRequest__1.Method = "POST"
webRequest__1.ContentType = contentType
webRequest__1.CookieContainer = cookies
webRequest__1.ContentLength = postBytes.Length
webRequest__1.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1"
webRequest__1.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
webRequest__1.Referer = "http://service.someurl.com/process.xml"
webRequest__1.Credentials = siteCredentials
Try
Dim requestStream As Stream = webRequest__1.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
Dim responseReader As New StreamReader(webRequest__1.GetResponse().GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
webRequest__1.GetResponse().Close()
Catch ex As Exception
Lbl_ConnTest_error.Text = ex.Message
End Try
End Sub
You need to send the bytes of the postString not the string itself:
Dim postBytes As Byte() = Encoding.UTF8.GetBytes(postString)
...
webRequest__1.ContentLength = postBytes.Length
...
Dim requestStream As Stream = webRequest__1.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
More information here.
Related
I am trying to send emails through gmail host by using google oauth 2.0, I am confused where to use the access code instead of user password to send emails,
this code is used to open up the consent screen and ask for permissions,
Dim Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" & googleplus_redirect_url & "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile%20https://mail.google.com/%20https://www.googleapis.com/auth/gmail.send&client_id=" + googleplus_client_id
Session("loginWith") = "google"
Response.Redirect(Googleurl)
after getting permissions, this is how I obtained access code,
If url <> "" Then
Dim queryString As String = url.ToString()
Dim delimiterChars As Char() = {"="c}
Dim words As String() = queryString.Split(delimiterChars)
Dim code As String = words(1)
If code IsNot Nothing Then
Dim webRequest As HttpWebRequest = CType(webRequest.Create("https://accounts.google.com/o/oauth2/token"), HttpWebRequest)
webRequest.Method = "POST"
Parameters = "code=" & code & "&client_id=" & googleplus_client_id & "&client_secret=" + googleplus_client_secret & "&redirect_uri=" + googleplus_redirect_url & "&grant_type=authorization_code"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(Parameters)
webRequest.ContentType = "application/x-www-form-urlencoded"
webRequest.ContentLength = byteArray.Length
Dim postStream As Stream = webRequest.GetRequestStream()
postStream.Write(byteArray, 0, byteArray.Length)
postStream.Close()
Dim response As WebResponse = webRequest.GetResponse()
postStream = response.GetResponseStream()
Dim reader As StreamReader = New StreamReader(postStream)
Dim responseFromServer As String = reader.ReadToEnd()
Dim serStatus As GooglePlusAccessToken = JsonConvert.DeserializeObject(Of GooglePlusAccessToken)(responseFromServer)
If serStatus IsNot Nothing Then
Dim accessToken As String = String.Empty
accessToken = serStatus.access_token
If Not String.IsNullOrEmpty(accessToken) Then
getgoogleplususerdataSer(accessToken)
End If
End If
End If
End If
and using the below code to send emails:
mm.Subject = LetterSubject.Text
Dim body As String
body = LetterBody.Text
mm.Body = body
Dim smtp As New Mail.SmtpClient()
smtp.Host = "smtp.gmail.com"
smtp.EnableSsl = True
smtp.Port = 587
smtp.UseDefaultCredentials = False
Dim service = New GmailService(New BaseClientService.Initializer With {.HttpClientInitializer = cred})
Dim NetworkCred As New NetworkCredential(SenderEmailAddress.Text, SenderPassword.Text)
smtp.Credentials = NetworkCred
smtp.Send(mm)
Can someone please help me how to use token here to send emails without using the user gmail password?
Imports System
Imports System.Threading.Tasks
Imports Google.Apis.Discovery.v1
Imports Google.Apis.Discovery.v1.Data
Imports Google.Apis.Services
Class Program
<STAThread>
Private Shared Sub Main(ByVal args As String())
Console.WriteLine("Discovery API Sample")
Console.WriteLine("====================")
Try
New Program().Run().Wait()
Catch ex As AggregateException
For Each e In ex.InnerExceptions
Console.WriteLine("ERROR: " & e.Message)
Next
End Try
Console.WriteLine("Press any key to continue...")
Console.ReadKey()
End Sub
Private Async Function Run() As Task
Dim service = New DiscoveryService(New BaseClientService.Initializer With {
.ApplicationName = "Discovery Sample",
.ApiKey = "[YOUR_API_KEY_HERE]"
})
Console.WriteLine("Executing a list request...")
Dim result = Await service.Apis.List().ExecuteAsync()
If result.Items IsNot Nothing Then
For Each api As DirectoryList.ItemsData In result.Items
Console.WriteLine(api.Id & " - " + api.Title)
Next
End If
End Function
End Class
''Your Authentication key should be static
''Dim NetworkUserName As String= "apikey"
' Dim YOUR_API_KEY_HERE As String = "SG.EEyBZDVAS622C6Rt7yu1sw.jwRdfkjJddfsJfgfsyuJuyuHutytr876RuQsffhghdf1d"
I'm looking for a way to convert the following cURL to ASP.Net.
curl -F f=#example.pdf "https://pdftables.com/api?key=ZZZ999&format=xml"
I've used the following function extensively to get virtually any URL/content, but I'm lost on how to include a file located on the hosted web server.
Public Shared Function GetRemoteURL(getURL As String) As String
Dim objReq As HttpWebRequest
Dim objRsp As HttpWebResponse = Nothing
Dim objRdr As StreamReader
Dim objRes As String = ""
Try
objReq = DirectCast(WebRequest.Create(getURL), HttpWebRequest)
objRsp = DirectCast(objReq.GetResponse(), HttpWebResponse)
objRdr = New StreamReader(objRsp.GetResponseStream())
objRes = objRdr.ReadToEnd()
Catch
objRes = ""
Finally
If Not objRsp Is Nothing Then objRsp.Close()
End Try
Return objRes.ToString()
End Function
Any advice/direction would be deeply appreciated.
John
You'll have to set the request body, something like:
Public Function GetRemoteURL(getURL As String) As String
Dim objReq As HttpWebRequest
Dim objRsp As HttpWebResponse = Nothing
Dim objRdr As StreamReader
Dim objRes As String = ""
Try
objReq = DirectCast(WebRequest.Create(getURL), HttpWebRequest)
objReq.Method = "POST"
Dim postData = "f=#example.pdf"
Dim encoding As New ASCIIEncoding()
Dim bytes = encoding.GetBytes(postData)
objReq.ContentLength = bytes.Length
Dim stream = objReq.GetRequestStream()
stream.Write(bytes, 0, bytes.Length)
objRsp = DirectCast(objReq.GetResponse(), HttpWebResponse)
objRdr = New StreamReader(objRsp.GetResponseStream())
objRes = objRdr.ReadToEnd()
Catch
objRes = ""
Finally
If Not objRsp Is Nothing Then objRsp.Close()
End Try
Return objRes.ToString()
End Function
note: i didn't test this so it might not directly work.
I'm trying to take the following curl command and use it in my vb.net page to connect to 3rd party.
curl -X POST -i -H "Accept: application/json" -u someusername:somepassword "https://domain.com/xyz/api/user" -d 'firstName=john&lastName=smith&ssn=111223333¤tAddress=1 Main ST¤tCity=somecity¤tState=WA¤tZip=99999'
Command above work fine in cygwin and I've tried to convert it to following but no luck. I tried encoding the password but that didn't help either. I would appreciate any help with this. Thank you!
Dim url As String = "https://domain.com/xyz/api/user"
Dim data As String = "{""CurrentAddress"":""1 Main St"", ""CurrentCity"":""Somecity"",""CurrentState"":""WA"",""CurrentZip"":""99999"",""FirstName"":""john"",""LastName"":""smith"",""ssn"":""111223333""}"
Dim myReq As WebRequest = WebRequest.Create(url)
myReq.Method = "POST"
myReq.ContentLength = data.Length
myReq.ContentType = "application/json"
myReq.Credentials = New NetworkCredential("someusername", "somepassword")
Using ds As Stream = myReq.GetRequestStream()
ds.Write(System.Text.ASCIIEncoding.Default.GetBytes(data), 0, data.Length)
End Using
Dim wr As WebResponse = myReq.GetResponse()
Dim receiveStream As Stream = wr.GetResponseStream()
Dim reader As New StreamReader(receiveStream, Encoding.UTF8)
Dim content As String = reader.ReadToEnd()
MsgBox(content)
After messing with it for two days, I was able to get it to work. here is the solution that I came up with.
Dim paramName As String() = New String(6) {"firstName", "lastName", "ssn", "currentAddress", "currentCity", "currentState", "currentZip"}
Dim paramVal As String() = New String(6) {"John", "Smith", "111223333", "1 main st", "any city", "dc", "11111"}
Dim result As String
result = HttpPost("https://domain.com/XYZ/api/user", paramName, paramVal)
Private Shared Function HttpPost(url As String, paramName As String(), paramVal As String()) As String
Dim req As HttpWebRequest = TryCast(WebRequest.Create(New Uri(url)), HttpWebRequest)
req.Method = "POST"
req.ContentType = "application/x-www-form-urlencoded"
req.Headers("Authorization") = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("myusername:mypassword"))
' Build a string with all the params, properly encoded.
' We assume that the arrays paramName and paramVal are
' of equal length:
Dim paramz As New StringBuilder()
For i As Integer = 0 To paramName.Length - 1
paramz.Append(paramName(i))
paramz.Append("=")
paramz.Append(HttpUtility.UrlEncode(paramVal(i)))
paramz.Append("&")
Next
' Encode the parameters as form data:
Dim formData As Byte() = UTF8Encoding.UTF8.GetBytes(paramz.ToString())
req.ContentLength = formData.Length
' Send the request:
Using post As Stream = req.GetRequestStream()
post.Write(formData, 0, formData.Length)
End Using
' Pick up the response:
Dim result As String = Nothing
Using resp As HttpWebResponse = TryCast(req.GetResponse(), HttpWebResponse)
Dim reader As New StreamReader(resp.GetResponseStream())
result = reader.ReadToEnd()
End Using
Return result
End Function
Am trying to create a simple page that connects to an external website, logs in, and then passes a bunch of parameters.
When I run the page I get a bad request 400 error and when I check using Fiddler I can see there are both 401 and 400 errors being returned. Under 'Auth' in Fiddler I see:
"No Proxy-Authorization Header is present.
No Authorization Header is present." < Is this relevant? As when I test using PHP cUrl the page can log in fine and Fiddler says the same under Auth.
Dim UserName As String = "testusername"
Dim password As String = "testpassword"
Dim siteCredentials As New NetworkCredential(UserName, password)
Dim URLAuth As String = "http://service.someurl.com/process.xml"
Dim postString As String = String.Format("customeremailaddress={0}&customername={1}&referenceid={2}&languagecode={3}&expirydays={4}", customeremailaddress, customername, referenceid, languagecode, expirydays)
Dim postBytes As Byte() = Encoding.UTF8.GetBytes(postString)
Const contentType As String = "application/x-www-form-urlencoded"
System.Net.ServicePointManager.Expect100Continue = False
Dim cookies As New CookieContainer()
Dim webRequest__1 As HttpWebRequest = TryCast(WebRequest.Create(URLAuth), HttpWebRequest)
webRequest__1.Method = "POST"
webRequest__1.ContentType = contentType
webRequest__1.CookieContainer = cookies
webRequest__1.ContentLength = postBytes.Length
webRequest__1.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1"
webRequest__1.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
webRequest__1.Referer = "http://service.someurl.com/process.xml"
webRequest__1.Credentials = siteCredentials
Try
Dim requestStream As Stream = webRequest__1.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
Dim testcapture As String = requestStream.ToString
Dim thing As String = "stop"
Dim responseReader As New StreamReader(webRequest__1.GetResponse().GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
webRequest__1.GetResponse().Close()
Catch ex As Exception
Lbl_ConnTest_error.Text = ex.Message
End Try
Seems the login credentials are not being passed what am I doing wrong? I am obviously using vb in an asp.net application but am connecting to an XML file held on Linux Apache, does this have any implications at all?
Fiddler appears to be doing strange things for me now so if anyone else can see anything using Fiddler a link to the test file is here:
http://www.filemanage.co.uk/Pubs/Default.aspx
I have a web application that sends the contents of a form to another site. This other i can pass the log in information without issue and the page authenticates alright but I don't know how to pass an array of information that is required at the other end. The array contain setting names and their respective setting values. I have this working in PHP but don't know how to do it in ASP.net
In PHP I use this for the array:
$aParams = array(
'customeremailaddress' => 'mr.test#test.com',
'customername' => 'mr test',
'exlibrisfile' => '#/ePubs/Ex-Libris.png'
);
And to send the array:
curl_setopt($rCurl, CURLOPT_POSTFIELDS, $aParams);
Here is the VB code I have ended up with that returns a 400 bad request error:
Dim postString As String = String.Format("customeremailaddress={0}&customername={1}&referenceid={2}&languagecode={3}&expirydays={4}", customeremailaddress, customername, referenceid, languagecode, expirydays)
Dim postBytes As Byte() = Encoding.UTF8.GetBytes(postString)
webRequest__1.ContentLength = postBytes.Length
Dim requestStream As Stream = webRequest__1.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
The complete code:
Public Sub TestConn()
Dim customeremailaddress As String = "mr.test#test.com"
Dim customername As String = "mr test"
Dim referenceid As String = "ordertest123"
Dim languagecode As String = "1043"
Dim expirydays As String = "30"
Dim UserName As String = "testusername"
Dim password As String = "testpassword"
Dim siteCredentials As New NetworkCredential(UserName, password)
Dim URLAuth As String = "http://service.someurl.com/process.xml"
Dim postString As String = String.Format("customeremailaddress={0}&customername={1}&referenceid={2}&languagecode={3}&expirydays={4}", customeremailaddress, customername, referenceid, languagecode, expirydays)
Dim postBytes As Byte() = Encoding.UTF8.GetBytes(postString)
Const contentType As String = "application/x-www-form-urlencoded"
System.Net.ServicePointManager.Expect100Continue = False
Dim cookies As New CookieContainer()
Dim webRequest__1 As HttpWebRequest = TryCast(WebRequest.Create(URLAuth), HttpWebRequest)
webRequest__1.Method = "POST"
webRequest__1.ContentType = contentType
webRequest__1.CookieContainer = cookies
webRequest__1.ContentLength = postBytes.Length
webRequest__1.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1"
webRequest__1.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
webRequest__1.Referer = "http://service.someurl.com/process.xml"
webRequest__1.Credentials = siteCredentials
Dim requestStream As Stream = webRequest__1.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
Dim requestWriter As New StreamWriter(webRequest__1.GetRequestStream())
Dim responseReader As New StreamReader(webRequest__1.GetResponse().GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
webRequest__1.GetResponse().Close()
End sub
This is my code to post data to another url.
Text is the form url-econded string.
Hope this can help
C#
private string PostData(string text)
{
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(text);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
using(WebResponse response = request.GetResponse())
using (Stream dataStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(dataStream))
{
return reader.ReadToEnd();
}
}
VB.NET
Private Function PostData(text As String) As String
Dim request As WebRequest = WebRequest.Create(url)
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(text)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Using dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
End Using
Using response As WebResponse = request.GetResponse()
Using dataStream As Stream = response.GetResponseStream()
Using reader As New StreamReader(dataStream)
Return reader.ReadToEnd()
End Using
End Using
End Using
End Function