While debugging this code fragment ,this error occurs - c#

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.

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

GetResponse keeps throwing page not found exception

Can you please help me out here? I am trying to get content of any web page. But GetResponse keeps throwing exception page not found. I appreciate your help. Following is my code.
try
{
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.smallchiptechnologies.com/");
request.Method = "POST";
request.ContentType = "text/plain";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
}
First, it looks like it should be GET response, not POST (since you just trying to get data from server and not posting any form data or something similar) so change request.Method = "POST"; to request.Method = "GET";
Second, you're not reading anything from response stream. Add something like this to your code to get page content:
string text;
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
text = reader.ReadToEnd();
}
Have you discarded potential proxy issues? For example, if you are running that code behind a corporate webproxy, you'll need to modify slightly your code in order to support the connection thru that proxy.
Something like this...
webrequest.Proxy = new WebProxy(ProxyServer,ProxyPort);
More details here: https://msdn.microsoft.com/en-us/library/czdt10d3(v=vs.110).aspx

Xml response file: Received in browser, not via 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.

Error when post message from C# program with server using Twisted python

My Method to post a message to server using C# .NET 4.0
private String postHTTP(String url)
{
String result = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
string postData = "Data has Posted";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
**request.ContentType = "application/x-www-form-urlencoded";**
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
txtWebServerStatus.Text = ((HttpWebResponse)response).StatusDescription;
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
my server code to provide a form to type and print what you type in form
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.web.error import NoResource
import cgi
class DynamicPage(Resource):
def render_GET(self, request):
return '<html><body><form method="POST"><input name="the-field" type="text" /></form></body></html>'
def render_POST(self, request):
return '<html><body>You submitted: %s</body></html>' % (cgi.escape(request.args["the-field"][0]),)
root = Resource()
dynamic = DynamicPage()
root.putChild("fool", dynamic)
factory = Site(root)
reactor.listenTCP(7777, factory)
reactor.run()
Error on post method:
in line WebResponse response = request.GetResponse();
The remote server returned an error: (500) Internal Server Error.
When I using post method have error on server:
C:\Users\sepdau>C:\Python27\python.exe E:\server.py
Unhandled Error Traceback (most recent call last):
File "C:\Python27\lib\site-packages\twisted\web\http.py", line 1349, in dataReceived finishCallback(data[contentLength:])
File "C:\Python27\lib\site-packages\twisted\web\http.py", line 1563, in _finishRequestBodyself.allContentReceived()
File "C:\Python27\lib\site-packages\twisted\web\http.py", line 1618, in allContentReceived req.requestReceived(command, path, version)
File "C:\Python27\lib\site-packages\twisted\web\http.py", line 773, in request Received self.process()
--- <exception caught here> ---
File "C:\Python27\lib\site-packages\twisted\web\server.py", line 132, in process
self.render(resrc)
File "C:\Python27\lib\site-packages\twisted\web\server.py", line 167, in render
body = resrc.render(self)
File "C:\Python27\lib\site-packages\twisted\web\resource.py", line 216, in render
return m(request)
**File "E:\server.py", line 25, in render_POST
return '<html><body>You submitted: %s</body></html>' % (cgi.escape(request.a
rgs["the-field"][0]),)
exceptions.KeyError: 'the-field'**
I think error on Server or ContentType I use no correct.
Can you help me.
Thank for advance.
So the problem you're hitting is:
KeyError: 'the-field'
This is because your client is posting:
Data has Posted
There are no form fields in that post data. There are two things you probably want to do.
First, make your server more robust against bad input. It's already somewhat robust: bad input generates a 500, but the server continues to operate and process future requests. You might want to generate a more useful error page to help clients figure out what they're doing wrong, though. So, try handling the KeyError:
def render_POST(self, request):
try:
value = request.args["the-field"][0]
except KeyError:
value = "<missing the-field value>"
return '<html><body>You submitted: %s</body></html>' % (cgi.escape(value),)
Now your client should get a 200 response, even if it keeps submitting form data without the form field the server is looking for.
Next, fix your client to submit post data that includes the correct form fields. Try a string like:
the-field=%5B%27some+value%27%5D
You can generate this in Python using urllib.urlencode, eg:
urllib.urlencode({'the-field': ['some value']})

Webrequest not working in a Windows Service

I am not able to use Webrequest in a windows service. It fails with error ""Unable to connect to the remote server".
WebRequest request = WebRequest.Create(url);
NetworkCredential nc = new NetworkCredential("myuname","mypassword","mydomain");
request.Proxy.Credentials = nc;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
}
catch (WebException ex)
{
//ex.Message is "Unable to connect to the remote server"
}
The code works perfectly fine if it is a console application.
Could someone please tell if there is a fix?
You might want to try specifying the proxy server on the request object you've created. When you run the console application I believe that the system looks up your IE configuration for you and the proxy may be set. If the service is running under an account other than yours it might not have the proxy set.
I was facing the same problem. After lots of R&D a solution worked for me.
Instead of:
WebResponse responseObject = requestObject.GetResponse();
I wrote:
WebResponse responseObject = null;
responseObject = requestObject.GetResponse();
and it worked fine.
I am also looking for the exact reason behind this behavior.

Categories