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.
Related
Try
Dim url = "something"
Dim request = WebRequest.Create(url)
request.Credentials = CredentialCache.DefaultCredentials
Dim httpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim dataStream = httpWebResponse.GetResponseStream()
If dataStream Is Nothing Then
Return ""
End If
Dim reader = New StreamReader(dataStream)
Return reader.ReadToEnd()
Catch ex As WebException
Return ""
End Try
Above code is working in LocalHost but in server it's not working and throwing an Exception.
System.Net.WebException' occurred in System.dll but was not handled
in user code
You're re-throwing the exception after the Catch.
Remove Throw.
Try
Dim url = "something"
Dim request = WebRequest.Create(url)
request.Credentials = CredentialCache.DefaultCredentials
Dim httpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim dataStream = httpWebResponse.GetResponseStream()
If dataStream Is Nothing Then
Return ""
End If
Dim reader = New StreamReader(dataStream)
Return reader.ReadToEnd()
Catch ex As WebException
Return ""
End Try
I am using the following code to try and learn how pages post, listen and respond between one another using web requests. I begin the process by issuing a request in the first of the two procedures, intending to have the second process retrieve the request and respond back to the calling process. My calling process is receiving a blank response.
Question: Why, and how close to viable is this test?
Here's my two page load events, located in two separate web applications.
Both apps are hosted on IIS:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sPostURL As String = "http://localhost/DDI_TXListener_Test/Listener_Page.aspx"
Dim dataToPost As String = String.Empty ' //This is the data for form posting
Dim HttpWebResponse As System.Net.WebResponse = Nothing
Dim StreamReader As System.IO.StreamReader = Nothing
Dim respString As String = String.Empty
Dim stOut As System.IO.Stream = Nothing
dataToPost = "Name"
Try
Dim httpReq As System.Net.WebRequest = System.Net.WebRequest.Create(sPostURL)
httpReq.Method = "POST"
httpReq.ContentType = "application/x-www-form-urlencoded"
Dim byte1 As Byte() = System.Text.Encoding.ASCII.GetBytes(dataToPost)
httpReq.ContentLength = byte1.Length
httpReq.Timeout = 10000
stOut = httpReq.GetRequestStream()
stOut.Write(byte1, 0, byte1.Length)
stOut.Dispose()
stOut = Nothing
HttpWebResponse = httpReq.GetResponse()
StreamReader = New System.IO.StreamReader(HttpWebResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"))
respString = StreamReader.ReadToEnd()
Catch ex As Exception
Finally
If Not StreamReader Is Nothing Then
StreamReader.Dispose()
StreamReader = Nothing
End If
If Not HttpWebResponse Is Nothing Then
HttpWebResponse.Close()
HttpWebResponse = Nothing
End If
End Try
' <asp:label> control on the html form in front of this code page
returnedhit.Text = respString
End Sub
And I have this as what I hope to use as the receiving/fulfilling end of the above request at:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sPostURL As String = "http://localhost/DDI_TXRequester_Test/RequesterPage.aspx"
Dim dataToPost As String = String.Empty ' //This is the data for form posting
Dim HttpWebResponse As System.Net.WebResponse = Nothing
Dim StreamReader As System.IO.StreamReader = Nothing
Dim respString As String = String.Empty
Dim stOut As System.IO.Stream = Nothing
Try
Dim httpReq As System.Net.WebRequest = System.Net.WebRequest.Create(sPostURL)
HttpWebResponse = httpReq.GetResponse()
StreamReader = New System.IO.StreamReader(HttpWebResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"))
respString = StreamReader.ReadToEnd()
If respString <> "" Then
Dim cnt As Integer = 0
Dim delim As Char() = {"&"c}
Dim bodpos As Integer = InStr(respString, "<body>") + 6
Dim respstr As String = Right$(respString, (Len(respString) - bodpos))
Dim strArr As String() = respstr.Split(delim)
For Each s As String In strArr
cnt += 1
Select Case cnt
Case 1
Session.Add("opRequested", Right$(Trim(s), (Len(Trim(s)) - 18)))
Case Else '
End Select
Next s
If CStr(Session("opRequested")) = "Name" Then dataToPost = "Name=Jones" Else dataToPost = "Error=Unknown Request"
httpReq.Method = "POST"
httpReq.ContentType = "application/x-www-form-urlencoded"
Dim byte1 As Byte() = System.Text.Encoding.ASCII.GetBytes(dataToPost)
httpReq.ContentLength = byte1.Length
httpReq.Timeout = 10000
stOut = httpReq.GetRequestStream()
stOut.Write(byte1, 0, byte1.Length)
stOut.Dispose()
stOut = Nothing
End If
Catch ex As Exception
Finally
If Not stOut Is Nothing Then
stOut.Dispose()
stOut = Nothing
End If
If Not StreamReader Is Nothing Then
StreamReader.Dispose()
StreamReader = Nothing
End If
If Not HttpWebResponse Is Nothing Then
HttpWebResponse.Close()
HttpWebResponse = Nothing
End If
End Try
End Sub
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
I cannot seem to understand what I'm doing wrong here.
My code below keeps returning a 400 code from youtube....
If Not Page.Request.QueryString("code") Is Nothing Then
Dim code As String = "code=" & Page.Request.QueryString("code") & "&client_id=myclientid&client_secret=mysecret&redirect_uri=http://localhost:61163/Testing/YoutubeAPI.aspx&grant_type=authorization_code"
Dim request As HttpWebRequest = WebRequest.Create("https://accounts.google.com/o/oauth2/token")
Dim byteData As Byte() = Encoding.UTF8.GetBytes(code)
With request
.Method = "POST"
.ContentType = "application/x-www-form-urlencoded"
.ContentLength = byteData.Length
End With
Dim requestStream As Stream = request.GetRequestStream()
requestStream.Write(byteData, 0, byteData.Length)
requestStream.Close()
Dim WebResponse As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim responseStream As Stream = WebResponse.GetResponseStream()
Dim sb As StringBuilder = New StringBuilder
Using reader As New StreamReader(responseStream, System.Text.Encoding.UTF8)
Dim line As String = reader.ReadLine()
If Not line Is Nothing Then
sb.Append(line)
End If
End Using
End If
the error occurs at request.GetRequestStream()... the best I can figure out at this stage is that google doesn't like what i'm asking for but cannot seem to find out why?
(My client ID and secret have been swopped incidentally....)
well am not sure if the etiquette is correct here in answering my own question but you may find it useful nonetheless.
The answer lay in the URL encoding of content string...
so now slightly amended the awesomeness of OAuth2 is unleashed and I can get pretty much whatever I want from the youtube API :) (although NO thanks to the black hole rabbit-hole of google documentation...
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.Request.QueryString("code") Is Nothing Then
Dim Token As String = CodeTrade("code=" & Server.UrlEncode(Page.Request.QueryString("code")) & "&redirect_uri=" & Server.UrlEncode("http://localhost:61163/Testing/YoutubeAPI.aspx") & "&client_id=xxx=&client_secret=xxx&grant_type=authorization_code")
'now i CAN do something with the magical and elusive access_token from this point forward....
End If
End Sub
Public Shared Function CodeTrade(code As String) As String
Dim apiResponse As String
Dim postData As String = code
Dim request As HttpWebRequest = DirectCast(WebRequest.Create("https://accounts.google.com/o/oauth2/token"), HttpWebRequest)
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
apiResponse = DirectCast(response, HttpWebResponse).StatusDescription.ToString()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
Return responseFromServer
End Function
Consider this code:
Dim strUrl As String = "http://www.txtguru.in/imobile/api.php?username=username&password=password&source=senderid&dmobile=123456789012&message=message"
Dim request As WebRequest = HttpWebRequest.Create(strUrl)
Dim response As HttpWebResponse = DirectCast(request.EndGetResponse(), HttpWebResponse)
Dim s As Stream = DirectCast(response.GetResponseStream(), Stream)
Dim readStream As New StreamReader(s)
Dim dataString As String = readStream.ReadToEnd()
response.Close()
s.Close()
readStream.Close()
I get an error on request.EndGetResponse() and the error is:
Argument not specified for parameter 'asyncResult' of 'Public Overridable Function EndGetResponse(asyncResult As System.IAsyncResult) As System.Net.WebResponse'.
How can I fix it?
Did you mean to use the asynchronous version:
Dim response As HttpWebResponse = DirectCast(request.EndGetResponse(), HttpWebResponse)
Try using the synchronous one instead:
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Try changing -
Dim response As HttpWebResponse = DirectCast(request.EndGetResponse(), HttpWebResponse)
to
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)