Xml response file: Received in browser, not via C# - c#

I'm trying to access the last.fm APIs via C#. As a first test I'm querying similar artists if that matters.
I get an XML response when I pass a correct artist name, i.e. "Nirvana". My problem is when I deliver an invalid name (i.e. "Nirvana23") I don't receive XML but an error code (403 or 400) and a WebException.
Interesting thing: If I enter the URL inside a browser (tested with Firefox and Chrome) I receive the XML file I want (containing a lastfm specific error message).
I tried both XmlReader and XDocument:
XDocument doc = XDocument.Load(requestUrl);
and HttpWebRequest:
string httpResponse = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
HttpWebResponse response = null;
StreamReader reader = null;
try
{
response = (HttpWebResponse)request.GetResponse();
reader = new StreamReader(response.GetResponseStream());
httpResponse = reader.ReadToEnd();
}
The URL is something like "http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist=Nirvana23" (and a specific key given by lastfm, but even without it - it should return XML). A link to give it a try: link (this is the error file I cannot access via C#).
What I also tried (without success): comparing the request by both the browser and my program with the help of WireShark. Then I added some headers to the request, but that didn't help either.

In .NET the WebRequest is converting HTTP error codes into exceptions, while your browser is just ignoring them since the response is not empty. If you catch the exception then the GetResponseStream method should still return the error XML that you are expecting.
Edit:
Try this:
string httpResponse = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
WebResponse response = null;
StreamReader reader = null;
try
{
response = request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response;
}
reader = new StreamReader(response.GetResponseStream());
httpResponse = reader.ReadToEnd();

Why don't you catch the exception and then process that accordingly. If you want to display any custom error, you can do that also in your catch block.

Related

HttpWebRequest No Response when calling an external website API

I am trying to use an API that helps detect bad IP, with C# code.
Here is the documentation.
How to call the API?
API requests are sent in a specific form. The API key is sent directly to the URL, as is the IP address from which you want to retrieve the information. This is the form of the URL called.
https://api.ipwarner.com/API-KEY/IP
According to this, I wrote a function:
private static string Get(string uri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException());
return reader.ReadToEnd();
}
And called it with:
string myresult = Get("https://api.ipwarner.com/myapikey/myip");
However, it got stuck at HttpWebResponse. There was no response at all.
(I confirm my API key is available and the input IP is right)
How's that wrong?
Please set time out and Try. Now, You will get the error message. Work on the error.
private static string Get(string uri)
{
string returnStr = trsing.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Timeout=10;
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream ?? throw new
InvalidOperationException());
returnStr = reader.ReadToEnd();
}
catch( Exception ex)
{
Debug.Writeline( ex.ToString());
}
return returnStr ;
}
It's not your problem i have checked it right now and the api is down
you can also check
https://www.isitdownrightnow.com/api.ipwarner.com.html
i signed up the site and tested it my self the api site is down
contact there support

While debugging this code fragment ,this error occurs

While debugging this code fragment ,this error(Unable to connect remote server) occurs.I showed where error occured in comment line
private static string GetWebText(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.UserAgent = "A .NET Web Crawler";
WebResponse response = request.GetResponse();//errors occured here
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string htmlText = reader.ReadToEnd();
return htmlText;
}
You should try to figuere out what is wrong, it can be wrong url or something that goes wrong with the request / response. In order to look at the traffic behind your application I would suggest using Fiddler for checking what happens behind the scene.

Invalid Data HttpWebResponse from HttpWebRequest C#

I am trying to load an HttpWebResponse into an XmlDocument and am getting the exception "Data at the root level is invalid. Line 1, position 1". If I output the response to the Console I get "system.net.connectstream". The credentials don't seem to be my problem because if I enter an incorrect password my exception changes to the 404 error. Here is my code...
string username = "username";
string password = "password";
string url = "https://myurl.com";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Credentials = new NetworkCredential(username, password);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
XmlDocument xmlDoc = new XmlDocument();
Console.WriteLine(response.GetResponseStream());
xmlDoc.Load(response.GetResponseStream());
Thanks!
Calling ToString on GetResponseStream() isn't going to do much for you - Stream.ToString isn't overridden.
I suggest you use something like this for debugging::
// Prefer casting over "as" unless you're going to check it...
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
// For diagnostics, let's assume UTF-8
using (StreamReader reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
Then replace the middle section (with StreamReader) with the XmlDocument.Load call.
I suspect you'll see that it's basically invalid XML, but the above should show you what it really is.
EDIT: Your comment shows the data as:
{"messages":{"message":"1 Device(s) returned."},"devices":{"device":
{"#id":"00","uuid":"00000000","phonenumber":"000‌​000",
"user name":"0000","name":"Guy,Somebody","platform":"platform","os":"III",
"version":"1‌​.1.1"}},"appName":"someApp"}
That's JSON. It's not XML. Don't try to load it as XML. You have two options:
Change what you're requesting so that you get an XML response back, if the server supports it
Parse it as JSON (e.g. with Json.NET) instead of as XML.

How to retrieve content passed back from remote server when the server reponds with a System.Net.WebException 422

I am working with an api that also returns a valid xml string containing the error that was encountered on their system.
<?xml version="1.0" encoding="UTF-8"?>
<error>
<request>Request made to server</request>
<message>No user found for account 12345</message>
</error>
Is there any way to get that xml from the remote server out of the System.Net.WebException object?
Thanks in advance :)
Direct from the MSDN docs:
When WebException is thrown by a descendant of the WebRequest class,
the Response property provides the Internet response to the
application.
So if you are if you are getting the exception while reading the response, you should just be able to read the Response property to get the XML contents.
Sure ya can! Just need to throw a try-catch around your request.GetResponse(), catch a WebException and read from the exceptions Response property.
WebRequest request = WebRequest.Create("http://www.google.com/ohnoa404");
WebResponse response;
try
{
response = request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response;
}
String responseString = String.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseString = reader.ReadToEnd();
}

Reading remote file [C#]

I am trying to read a remote file using HttpWebRequest in a C# Console Application. But for some reason the request is empty - it never finds the URL.
This is my code:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://uo.neverlandsreborn.org:8000/botticus/status.ecl");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
How come this is not possible?
The file only contains a string. Nothing more!
How are you reading the response data? Does it come back as successful but empty, or is there an error status?
If that doesn't help, try Wireshark, which will let you see what's happening at the network level.
Also, consider using WebClient instead of WebRequest - it does make it incredibly easy when you don't need to do anything sophisticated:
string url = "http://uo.neverlandsreborn.org:8000/botticus/status.ecl";
WebClient wc = new WebClient();
string data = wc.DownloadString(url);
You have to get the response stream and read the data out of that. Here's a function I wrote for one project that does just that:
private static string GetUrl(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
throw new ServerException("Server returned an error code (" + ((int)response.StatusCode).ToString() +
") while trying to retrieve a new key: " + response.StatusDescription);
using (var sr = new StreamReader(response.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
}

Categories