VB.NET The remote server returned an error: (405) Method Not Allowed - vb.net

The below code works on some URLs, but some other URLs having parameters return the error: The remote server returned an error: (405) Method Not Allowed.
my work:
Dim objHttpWebRequest As HttpWebRequest = Nothing
Dim objHttpWebResponse As HttpWebResponse = Nothing
Dim objRequestStream As Stream = Nothing
Dim objResponseStream As Stream = Nothing
Dim objXMLReader As XmlTextReader
Try
objHttpWebRequest = WebRequest.Create(URL)
'Start HttpRequest
objHttpWebRequest.Method = "POST"
objHttpWebRequest.ContentType = "application/xml"
'Get Stream Object
objRequestStream = objHttpWebRequest.GetRequestStream()
objRequestStream.Close()
'Start HTTP Response
objHttpWebResponse = objHttpWebRequest.GetResponse()
If objHttpWebResponse.StatusCode = HttpStatusCode.OK Then
objResponseStream = objHttpWebResponse.GetResponseStream()
objXMLReader = New XmlTextReader(objResponseStream)
Dim xmldoc As XmlDocument = New XmlDocument
xmldoc.Load(objXMLReader)
XMLResponse = xmldoc
objXMLReader.Close()
End If
Is the problem in the method I am using? or the content type?

Based on the status code, the problem is in the method. Not all of the URLs might be able to respond to POST requests.
Wikipedia states
405 Method Not Allowed
A request was made of a resource using a request method not supported
by that resource; for example, using GET on a form which requires data
to be presented via POST, or using PUT on a read-only resource.

Related

Need help in solving error in HTTP GET request

Need help in solving error in HTTP GET request [closed]
I have the following code in VB.NET framework which should pull the data in json format and add it to a list view control using GET request. However I am getting following error:
System.Threading.Tasks.Task.FromResult(System.Net.Http.HttpResponseMessage)
Dim client = New HttpClient()
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{Subscription-Key}")
Dim uri = "https://example.com/" & SearchKey
Dim response = client.GetAsync(uri)
lstMer.Items.Add(response.ToString)
Initially I wrote the following code in VBA and it was working fine:
Dim jsonText as String
Set req = New MSXML2.ServerXMLHTTP60
key_id = "{Subscription-Key}"
key_header_name = "Subscription-Key-Id"
liveURL = "https://example.com/" & SearchKey
req.Open "GET", liveURL, False
req.setRequestHeader {Subscription-Key-Id}, {Subscription-Key}
req.setRequestHeader "Host", "site Address"
req.send
jsonText = req.responseText
The requirement is to get the headers from URL and fill a list view.
I think I understand. You don't get an error
System.Threading.Tasks.Task.FromResult(System.Net.Http.HttpResponseMessage)
rather you get that as a result of response.ToString(). This is because you are calling client.GetAsync(uri) directly, which returns a Task.FromResult<TResult>. However, it is meant to be run async, and there are some convenient keywords for achieving this, namely Async / Await. If you await the task, instead of returning a Task.FromResult<TResult>, it will return a TResult. So change your code to do just that
Private Async Sub Foo()
Dim client = New HttpClient()
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{Subscription-Key}")
Dim uri = "https://example.com/" & SearchKey
Dim response = Await client.GetAsync(uri)
lstMer.Items.Add(response.ToString)
End Sub
See HttpClient.GetAsync and about what it returns Task.FromResult

Empty response HTTPWebRequest: Windows Phone 8

I am making a Windows Phone app and I am trying to get JSON data from a URL. The user needs to be logged into the website (which hosts the JSON data) in order to get JSON data and I cannot use the Web Browser control to display the data and then extract the string since the browser doesn't recognize it (for some weird reason) and asks to search for an app on Store which can handle that JSON file type. (If I open the URL in desktop browser on my Windows PC, I can see the raw JSON data). I can't use normal HTTPWebRequest or WebClient as to get JSON data the login cookies needs to be set (the JSON data is user-specific) and I can't extract the cookies from Web browser control and use it with WebClient or HTTPWebRequest. So the best thing I can do is use a special internal instance of IWebRequestCreate that is used internally by the WebBrowser. By opening background HTTP requests with that class, the cookies get automatically set as if they were created/sent by the WebBrowser control. But my code is not returning the JSON data, I get blank response, as in the string resp is empty.
Below is the code:
Dim browser = New WebBrowser()
Dim brwhttp = GetType(WebRequestCreator).GetProperty("BrowserHttp")
Dim requestFactory = TryCast(brwhttp.GetValue(Browser, Nothing), IWebRequestCreate)
Dim uri = New Uri("http://api.quora.com/api/logged_in_user?fields=inbox,notifs,following,followers")
Dim req = requestFactory.Create(uri)
req.Method = "GET"
req.BeginGetResponse(New AsyncCallback(AddressOf request_Callback), req)
Private Sub request_Callback(asyncResult As IAsyncResult)
Dim webRequest As HttpWebRequest = DirectCast(asyncResult.AsyncState, HttpWebRequest)
Dim webResponse As HttpWebResponse = DirectCast(webRequest.EndGetResponse(asyncResult), HttpWebResponse)
Dim tempStream As New MemoryStream()
webResponse.GetResponseStream().CopyTo(tempStream)
Dim sr As New StreamReader(tempStream)
Dim resp As String = sr.ReadToEnd
End Sub
What's wrong?
I found that CopyTo can leave the Stream's pointer at the end of the buffer, you probably need to reset tempStream's pointer to the beginning before attempting to read it with the StreamReader, here's the code...
webResponse.GetResponseStream().CopyTo(tempStream);
tempStream.Seek(0, SeekOrigin.Begin);
Dim sr As New StreamReader(tempStream);

Getting multiple SQL Reports with HttpWebRequest - 401 Unauthorized

I am trying to call multiple SQL Reporting Services Reports, get the .pdfs back, then append them together. I have no problems appending .pdfs, but I'm getting an error on the second report. Here's some example code:
Dim httpReq As System.Net.HttpWebRequest = DirectCast(System.Net.WebRequest.Create(strLink), System.Net.HttpWebRequest)
Dim creds As New System.Net.NetworkCredential
creds.Domain = "MyDomain"
creds.UserName = "UserName"
creds.Password = "Password"
httpReq.Credentials = creds
Dim httpResp As System.Net.HttpWebResponse = DirectCast(httpReq.GetResponse(), System.Net.HttpWebResponse)
httpResp.Close()
httpReq = Nothing
httpResp = Nothing
Dim SecondHttpReq As System.Net.HttpWebRequest = DirectCast(System.Net.WebRequest.Create(strSecondLink), System.Net.HttpWebRequest)
SecondHttpReq.Credentials = creds
Dim SecondHttpResp As System.Net.HttpWebResponse = DirectCast(SecondHttpReq.GetResponse(), System.Net.HttpWebResponse)
When I try to create the second HttpResponse, I get a 401 Unauthorized error. When I check the SecondHttpReq object when it errors, I find that the Credentials property has been set back to Nothing. I've tried using a CookieContainer to no avail. I'd really rather not have to write a parent/sub report to get these together, so I'd like to hear other options. Thanks in advance.
Fixed. Someone changed permissions on our report server without notifying anyone.

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

How can I use VB.Net to read the content returned from a URL?

Below is the example code I'm using to get this to work and it does work if I try to read yahoo.com.
Here is the problem. The address I need to read is a java servlet that processes parameters passed in, generates a text document on the server, and then redirects to another URL and returns the address of the text file on the server. I then need to download that text file and process it. I'm having problems connecting to the first URL with the parameters and I think it has to do with the redirect.
I'm using the WebRequest object and I've tried using the HttpWebRequest object. Are there any other objects that support redirects?
TIA
Dim reader As StreamReader
Dim request As WebRequest
Dim response As WebResponse
Dim data As String = ""
Try
request = WebRequest.Create("URL Here")
request.Timeout = 30000
response = request.GetResponse()
reader = New StreamReader(response.GetResponseStream())
data = reader.ReadToEnd()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Return data
Edit
I just tested out HttpWebRequest.Create() and that does handle the 301 and 302 fine with out extra code.
Can you post the error you are seeing
You could cast the WebResponse to a HttpWebResponse:
I need to convert this to VB... but it might help you start:
var response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.Redirect)
{
// Follow Redirect, new request based off Redirect
}
// Read Data
I believe you just have to set the AutoRedirect property.
request.AutoRedirect = true;
webRequest = webRequest.Create(URL)
webresponse = webRequest.GetResponse()
inStream = New StreamReader(webresponse.GetResponseStream())
Read URL full source code
winston
I think I found something that will work.
I used a WebBrowser control instead.
Have a button that runs this code...
WebBrowser1.Navigate("URL Here")
And this function to process once the request returns.
Private Sub WebBrowser1_Navigated(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserNavigatedEventArgs) Handles WebBrowser1.Navigated
MsgBox(WebBrowser1.DocumentText)
End Sub