WebException in getResponse() - c#

here my code-
private string HttpContent(string url)
{
WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
StreamReader sr = new StreamReader(objRequest.GetResponse().GetResponseStream());
string result = sr.ReadToEnd();
sr.Close();
return result;
}
exception comes in 2nd line in objRequest.GetResponse(). If I open it quick watch window I get:
'objRequest.GetResponse()' threw an exception of type 'System.Net.WebException'
"The remote server returned an error:(404) Not Found."

That seems pretty self-explanatory, really; Check your URL to make sure you're hitting the right location, or make sure that your target server is actually running.

It says what it says:
The remote server returned an error:(404) Not Found.
Your URL does not exist on the server and is not recognised. Your client code is not optimal but should work.

This error message is as it declares, the URL that you requested came back as a 404 error meaning that the page was not found.
Now it is possible that they are doing some odd "redirect" so you might try setting
objRequest.AllowAutoRedirect = true;
and see if that helps. However based on the 404 rather than a 301 or 302 response I'm not sure it will make any difference.

Try to call Url from your browser, if you get response you will be sure that your Url is working. Maybe in your computer there is proxy, you have pass proxy in your code.
That may help you

the problem is that the path [url] is incorrect you pass to method().
the URL may be not well form or check the url that 's work or not. if you not sure that's should always correct then you can use try catch if you want.

Related

How can i retrieve the http response status code from an url?

I am automating a test for a page that contains a URL that needs to be then tested.
I created a method that I believed was giving me the http status code:
public string ContentUrlHttpRequest()
{
HttpWebRequest protocolWebRequest = (HttpWebRequest)WebRequest.Create(ContentUrl());
protocolWebRequest.Method = "GET";
HttpWebResponse response = (HttpWebResponse)protocolWebRequest.GetResponse();
return response.Headers.ToString();
}
ContentUrl() is another method i created to find the element on the page with the url to be tested and gets it's value.
I have also tried return response.StatusCode.ToString(); but the response i received was "OK".
I know that the response from that url needs to be = 200. I have this assertion that compares the response from the ContentUrlHttpRequest() to the expected results (200):
Assert.AreEqual("200", ContentUrlHttpRequest(), "The Url is not live. Http response = " + ContentUrlHttpRequest());
The response i am getting from ContentUrlHttpRequest() is not the status code but:"Date: Mon, 03 May 2021 09:07:13 GMT".
I understand why it is happening, it is getting the header of the page that is searching. But how could I get the status code? Is it possible with Selenium? Is there something wrong with my method and instead of Headers I need to use something different?
Unfortunately i am not able to provide with the urls that i am testing, or the platform with the url as they are confidential. Hopefully my issue is clear and you guys can give me some guidance.
You are not returning the response status code. You are returning the headers.
You should replace the return statement with this:
return ((int)response.StatusCode).ToString();
I guess you should use response.Status.ToString(); instead of response.Headers.ToString();
But the status contains not only the number like 200 or 401 but also text.
So if you are going to use response.Status.ToString(); you should Assert.True(ContentUrlHttpRequest().contains("200"))
Or you can use response.StatusCode.ToString(); this will give you the status number itself String without additional texts.

Autodesk Forge Error trying to access the API online

I have a problem loading a 3D model on an online server, the error shown is related to accessing the Forge API, locally works smoothly however when mounted on the server or a website is made marks the following error "Failed to load resource: the server responded with a status of 404 (Not Found)", then "onDocumentLoadFailure() - errorCode:7".
As I comment, what I find stranger is that, locally, it works. Attached the segment of the code where it displays the error.
function getAccessToken() {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", '/api/forge/toke', false); //Address not found
xmlHttp.send(null);
return xmlHttp.responseText;
}
Thank you very much in advance.
Are you sure the code you're running locally and the code you've deployed are really the same?
The getAccessToken function doesn't seem to be correct, for several reasons:
First of all, there seems to be a typo in the URL - shouldn't it be /api/forge/token instead of /api/forge/toke?
More importantly, the HTTP request is asynchronous, meaning that it cannot return the response immediately after calling xmlHttp.send(). You can find more details about the usage of XMLHttpRequest in https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest.
And finally, assuming that the function is passed to Autodesk.Viewing.Initializer options, it should return the token using a callback parameter passed to it (as shown in https://forge.autodesk.com/en/docs/viewer/v7/developers_guide/viewer_basics/initialization/#example).
With that, your getAccessToken should probably look more like this (using the more modern fetch and async/await):
async function getAccessToken(callback) {
const resp = await fetch('/api/forge/token');
const json = await resp.json();
callback(json.access_token, json.expires_in);
}
I've already found the issue. When I make the deploy I have to change the url where the request is made for the public or the name of the domain. For example: mywebsite.com/aplication-name/api/forge/token.

HttpClient.PostAsync fails if the ASP.NET server returns RedirectResult

On the server side I'm doing:
return Redirect(...); // <- doesn't matter which url
On client side I'm doing
await Http.PostAsync
It always gives an error..:
1- If I set it to "http://www.google.com" I get error:
System.Net.WebException: Error getting response stream (ReadDone2): ReceiveFailure ---> System.Exception: at System.Net.WebConnection.HandleError(WebExceptionStatus st, System.Exception e, System.String where)
2- If I set it to a relative url like "/", the await times out:
System.Threading.Tasks.TaskCanceledException: A task was canceled
I've been stuck on this problem for a long time, I've finally found that it's all because for some reason HttpClient doesn't like being redirected apparently.
The exact some thing works perfectly fine when I test it in RESTClient in Firefox.
Any ideas?
Edit: Please ignore this question, it's a problem with Mono, complete simple code to reproduce here:
https://forums.xamarin.com/discussion/42410/bug-httpclient-times-out-when-redirected-on-a-post-request

503 error with page content

I have a pretty annoying problem with my new program...
I want programmatically search queries on google.
its working great but after a while google returns me their captcha page, but it isn't a regular response, it is a statuscode of 503 service unabailable and it goes directly to the catch {} with this exception and I cant get the html content that I get when I do the same thing in the browser...
I researched it on the internet and found nothing about a 503 response with html content...
I just wondered how can I get the page html source from the 503 response
thank you very much...
I'm assuming you're getting a WebException. If so, you can access the HTTP response with something like...
try {
// Make the request...
} catch(WebException wexc) {
var httpResponse = (HttpWebResponse)wexc.Response;
if(httpResponse.StatusCode == HttpStatusCode.ServiceUnavailable) {
// You can read the response as usual here.
} else {
throw; // not something we care about, re-throw exception
}
}
Did you try to check there : Error 503 C#
Try to use Fiddler2 to get more information for us ... you can get this error from various things ...
Please check google TOS:
http://support.google.com/websearch/bin/answer.py?hl=en&answer=86640
This is the reason you are getting 503.
Here is a link which might help:
http://goohackle.com/break-google-captcha/

.NET HttpWebRequest HTTPS Error

Hello I'm trying to fetch data from a https web (i'm not behind firewall or proxy) however even accepting all certificates it keeps throwing System.Net.WebExceptionStatus.SecureChannelFailure with the message shown: Cancelled the request: Unable to create a secure SSL/TLS channel
... i've looked everywhere so you guys are my last chance.
static void Main(string[] args)
{
RemoteCertificateValidationCallback ServerCertificateValidationCallback = delegate { return true; };
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://miyoigo.yoigo.com");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Console.Write(reader.ReadToEnd());
}
}
Thanks in advance ;)
try printing the InnerException property of the WebException, should provide a particular reason the negot failed
Console.WriteLine("Inner Exception");
Console.WriteLine(String.Concat(e.InnerException.StackTrace, e.InnerException.Message));
That code works fine for me exactly as you have it. My guess is that you've got something network related going on. Are you behind a proxy or firewall? Like Ray said in his comment, try hitting that URL from a browser.
I have resolved my problem looking at:
How do you get a System.Web.HttpWebRequest object to use SSL 2.0?

Categories