I am trying to download a report off of our company website using VbNet. I have the following code:
Dim hwrequest As Net.HttpWebRequest = Net.HttpWebRequest.Create("https://delph.am.mycompany.com/apps/Reports/ExportDocument11.asp?ID=826&Request=List&OpenType=Edit")
hwrequest.CookieContainer = cookies
hwrequest.Accept = "*/*"
hwrequest.AllowAutoRedirect = False
hwrequest.UserAgent = "http_requester/0.1"
hwrequest.Timeout = 60000
hwrequest.Method = "GET"
Dim hwresponse As Net.HttpWebResponse = hwrequest.GetResponse()
If hwresponse.StatusCode = Net.HttpStatusCode.OK Then
Dim responseStream As IO.StreamReader = _
New IO.StreamReader(hwresponse.GetResponseStream())
responseData = responseStream.ReadToEnd()
End If
But the Response object just returns:
<head><title>Object moved</title></head>
<body><h1>Object Moved</h1>This object may be found <a HREF="/Security/ErrorTrap.asp?
ErrorID=7">here</a>.</body>
and the Location header of the response returns: {X=46,Y=46} and I am not sure what that means.
Can anyone please tell me what I am doing wrong? Thanks in advance.
Try changing hwrequest.AllowAutoRedirect = False to hwrequest.AllowAutoRedirect = True
hwrequest.UserAgent = "http_requester/0.1"
may also be causing you troubles.
Related
I am a beginner in the API ecosystem. I am using VB.NET to call API. Code used for the same given below:
Try
Dim s As HttpWebRequest
Dim enc As UTF8Encoding
Dim postdata As String
Dim postdatabytes As Byte()
Dim jo As New JObject
jo.Add("apiid", objProp.Text7)
jo.Add("apiData", objProp.Text8)
postdata = jo.ToString()
s = HttpWebRequest.Create(objProp.Text6)
enc = New System.Text.UTF8Encoding()
postdatabytes = enc.GetBytes(postdata)
s.Method = "POST"
s.ContentType = "application/json"
s.ContentLength = postdatabytes.Length
s.Headers.Add("user-name", "MjRKQGU1NypQJkxZYVpCdzJZXnpKVENmIXFGQyN6XkI=")
s.Headers.Add("api-key", "UjMhTDZiUlE1MkhMWmM2RkclJXJhWUJTTWZDeHVEeDQ=")
Using stream = s.GetRequestStream()
stream.Write(postdatabytes, 0, postdatabytes.Length)
End Using
Dim result = s.GetResponse()
Dim responsedata As Stream = result.GetResponseStream
Dim responsereader As StreamReader = New StreamReader(responsedata)
Dim xResponse = responsereader.ReadToEnd
Try
Dim opData = JObject.Parse(xResponse)("apiData").ToString
objProp = JsonConvert.DeserializeObject(Of default_prop)(opData)
Catch ex As Exception
End Try
Catch myerror As OracleException
'Status
objProp.Text5 = "500"
'Failure Response Message
objProp.Text11 = "Internal Server Error..."
db_close()
End Try
My issue is that I could not find the proper syntax to retrieve API Response Status Code from the response. Request your guidance
With some small changes on your code you can do the trick as follow:
'....... other code here
Using stream = s.GetRequestStream()
stream.Write(postdatabytes, 0, postdatabytes.Length)
End Using
Dim result As HttpWebResponse = CType(s.GetResponse(), HttpWebResponse)
Console.WriteLine(result.StatusCode)
I need away to disable chaching for my VB.NET code. I've found some hints in C#, but nothing that I can get to work.
Right now, when i send in a request, i'm getting the previous request results.
Here's my code:
Dim responseData As String = ""
Try
Dim cookieJar As New Net.CookieContainer()
Dim hwrequest As Net.HttpWebRequest = Net.WebRequest.Create(URL)
hwrequest.CookieContainer = cookieJar
hwrequest.Accept = "*/*"
hwrequest.AllowAutoRedirect = True
hwrequest.UserAgent = "http_requester/0.1"
hwrequest.Timeout = 60000
hwrequest.Method = method
'hwrequest.CachePolicy = CachePolicy
If hwrequest.Method = "POST" Then
hwrequest.ContentType = "application/x-www-form-urlencoded"
Dim encoding As New Text.ASCIIEncoding() 'Use UTF8Encoding for XML requests
Dim postByteArray() As Byte = encoding.GetBytes(POSTdata)
hwrequest.ContentLength = postByteArray.Length
Dim postStream As IO.Stream = hwrequest.GetRequestStream()
postStream.Write(postByteArray, 0, postByteArray.Length)
postStream.Close()
End If
Dim hwresponse As Net.HttpWebResponse = hwrequest.GetResponse()
If hwresponse.StatusCode = Net.HttpStatusCode.OK Then
Dim responseStream As IO.StreamReader =
New IO.StreamReader(hwresponse.GetResponseStream())
responseData = responseStream.ReadToEnd()
End If
hwresponse.Close()
cookieJar = Nothing
Catch e As Exception
responseData = "An error occurred: " & e.Message
End Try
Return responseData
End Function```
Any help would be appreciated!
I need help, none i can't seem to find a solution to my problem.
I'm trying to create a directory in FTP Server:
Dim request As FtpWebRequest = FtpWebRequest.Create("ftp:\\*******")
Dim creds As NetworkCredential = New NetworkCredential("****", "*****")
request.Credentials = creds
request.KeepAlive = True
request.EnableSsl = True
request.UsePassive = True
request.Timeout = 10000000
request.ReadWriteTimeout = 10000000
ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf customCertValidation)
Dim resp As FtpWebResponse = Nothing
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails
Using resp
resp = request.GetResponse()
Dim sr As StreamReader = New StreamReader(resp.GetResponseStream(), System.Text.Encoding.ASCII)
Dim s As String = sr.ReadToEnd()
If Not s.Contains("newfolder") Then
request = FtpWebRequest.Create("ftp:\\********")
request.Credentials = creds
request.Method = WebRequestMethods.Ftp.MakeDirectory
resp = request.GetResponse()
Console.WriteLine(resp.StatusCode & "Created")
Else
Console.WriteLine("Directory already exists")
End If
End Using
Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
Function for customCertValidation
Function customCertValidation(ByVal sender As Object,
ByVal cert As X509Certificate,
ByVal chain As X509Chain,
ByVal errors As SslPolicyErrors) As Boolean
Return True
End Function
I get the following error:
I have tried everything on the web but nothing seems to work, can someone please tell me what is wrong.
Thank You
This is driving me insane. I know I have to be close on this. My requests matches a real one as far as I can see except the cookies are a bit different. I appear to be missing the google analytics ones. Not sure if that is the issue or not. I get redirected like I am supposed to but on the redirect page it is asking me to login again. Any help is appreciated. Here is my code:
Private Function eaLogin(ByVal ticker As String, ByVal password As String)
Try
ServicePointManager.Expect100Continue = False
Dim request As HttpWebRequest = httpWebRequest.Create("http://www.empireavenue.com")
request.Credentials = CredentialCache.DefaultCredentials
request.CookieContainer = cookieJar
Dim response As HttpWebResponse = request.GetResponse()
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
response.Close()
Dim session As String = ""
ServicePointManager.Expect100Continue = False
'Set the initial parameters
Dim UserID As String = ticker ' Username
Dim PWord As String = HttpUtility.UrlEncode(password) ' Password
Dim domain As String = "https://www.empireavenue.com/user/login/do"
Dim encoding As New System.Text.ASCIIEncoding
' Use the appropriate HTML field names to stuff into the post header
Dim PostData As String = _
"login_username=" & ticker & _
"&login_password=" & PWord
Dim Data() As Byte = encoding.GetBytes(PostData)
' Initialise the request
Dim LoginReq As Net.HttpWebRequest = Net.WebRequest.Create(domain) ' Login location taken from the form action
With LoginReq
.KeepAlive = True
.Method = "POST"
' Note: if the page uses a redirect if will fail
.AllowAutoRedirect = False
.ContentType = "application/x-www-form-urlencoded"
.ContentLength = Data.Length
' Set empty container
.CookieContainer = cookieJar
.Referer = "http://www.empireavenue.com/"
.UserAgent = userAgent
.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
.Host = "www.empireavenue.com"
End With
' Add the POST data
Dim SendReq As IO.Stream = LoginReq.GetRequestStream
LoginReq.Headers.Add("Accept-Language", "en-US,en;q=0.5")
LoginReq.Headers.Add("Accept-Encoding", "gzip, deflate")
SendReq.Write(Data, 0, Data.Length)
SendReq.Close()
' Obtain the response
Dim LoginRes As Net.HttpWebResponse = LoginReq.GetResponse()
' Retreive the headers from the request (e.g. the location header)
Dim Redirect As String = LoginRes.Headers("Location")
' Add any returned cookies to the cookie collection
cookieJar.Add(LoginRes.Cookies)
' Move to the redirected page as a GET request...
Dim newUrl As String = ""
If Not (Redirect Is Nothing) Then
If Redirect.StartsWith("http://") Then
newUrl = Redirect
Else
newUrl = "https://www.empireavenue.com" & Redirect
End If
LoginReq = Net.WebRequest.Create(newUrl)
With LoginReq
.KeepAlive = False
.Method = "GET"
.ContentType = "application/x-www-form-urlencoded"
.AllowAutoRedirect = True
.CookieContainer = cookieJar
End With
' Perform the navigate and output the HTML
LoginRes = LoginReq.GetResponse()
Dim sReader As IO.StreamReader = New IO.StreamReader(LoginRes.GetResponseStream)
Dim HTML As String = sReader.ReadToEnd
If HTML.Contains(ticker) Then
MessageBox.Show("yay!")
Return True
Else
MessageBox.Show("no!")
Return False
End If
Else
MessageBox.Show("no too!")
Return False
End If
Catch ex As Exception
MessageBox.Show(ex.Message.ToString)
Return False
End Try
End Function
I couldn't try it on the empirevenue because of the restrictions at work but try this:
Dim tempCookies As CookieContainer
ServicePointManager.Expect100Continue = False
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("https://www.empireavenue.com/user/login/do"), HttpWebRequest)
Dim postData As String = "login_username=" & ticker & "&login_password=" & PWord
Dim encoding As New UTF8Encoding
Dim byteData As Byte() = encoding.GetBytes(postData)
postReq.Method = "POST"
postReq.KeepAlive = True
postReq.CookieContainer = tempCookies
postReq.ContentType = "application/x-www-form-urlencoded"
postReq.Referer = "http://www.empireavenue.com/"
postReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20120427 Firefox/15.0a1"
postReq.ContentLength = byteData.Length
Dim postreqstream As Stream = postReq.GetRequestStream()
postreqstream.Write(byteData, 0, byteData.Length)
postreqstream.Close()
Dim postresponse As HttpWebResponse
postresponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
tempCookies.Add(postresponse.Cookies)
logincookie = tempCookies
Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
Dim thepage As String = postreqreader.ReadToEnd
Hope it will work for you
i am using hammock twitter library to post and get the friends list from Twitter. Previously it was working fine. But now only the request_token part is working. While trying to get the access tokens and userid, screen name getting an "OK" server response. But the result looks likes this:
� �Dͻ�0#�as�"Ё��&b�����֔ԧ��8ߑ��h9�v�r<{g�/�XR>�eݻ.>~�rH�5�Z��_�~�+Kn9��)��£�sU��)��������|�TV6!�B��2(���֚V`�!��#4�� �� ��?d�
I dont know why i am getting this.. :(
below is my code
Public Sub GetRequestToken(Consumer_KEY As String, Consumer_Secret_Key As String)
Dim credentials = New OAuthCredentials
credentials.Type = OAuthType.RequestToken
credentials.SignatureMethod = OAuthSignatureMethod.HmacSha1
credentials.ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader
credentials.ConsumerKey = TwitterSettings.ConsumerKey
credentials.ConsumerSecret = TwitterSettings.ConsumerKeySecret
credentials.Version = TwitterSettings.OAuthVersion
credentials.CallbackUrl = "oob"
Dim client = New RestClient
client.Authority = "https://api.twitter.com/oauth"
client.Credentials = credentials
client.HasElevatedPermissions = True
Dim request = New RestRequest
request.Path = "/request_token"
client.BeginRequest(request, New RestCallback(AddressOf TwitterRequestTokenCompleted))
End Sub
Public Sub TwitterRequestTokenCompleted(request As RestRequest, response As RestResponse, userstate As Object)
result = Regex.Split(response.Content, "&")
oauth_token = Regex.Split(result(0), "=")(1)
oauth_secret_token = Regex.Split(result(1), "=")(1)
request_url = TwitterSettings.AuthorizeUri + "?oauth_token=" + oauth_token
case_url = "request"
Deployment.Current.Dispatcher.BeginInvoke(getresult)
End Sub
After parsing the oob pin, i am requesting for access tokens:
Public Sub GetAccessToken(Verifier As String)
Dim credentials = New OAuthCredentials
credentials.Type = OAuthType.AccessToken
credentials.SignatureMethod = OAuthSignatureMethod.HmacSha1
credentials.ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader
credentials.ConsumerKey = TwitterSettings.ConsumerKey
credentials.ConsumerSecret = TwitterSettings.ConsumerKeySecret
credentials.Token = oauth_token
credentials.TokenSecret = oauth_secret_token
credentials.Verifier = Verifier
Dim client = New RestClient
client.Authority = "https://api.twitter.com/oauth"
client.Credentials = credentials
client.HasElevatedPermissions = True
Dim request = New RestRequest
request.Path = "/access_token"
client.BeginRequest(request, New RestCallback(AddressOf RequestAccessTokenCompleted))
did anyone face this before? i need this asap.. just confused how this happened all of a sudden. Thanks in advance geeks ;)