As the title says I am trying to run a Windows Phone App which is supposed to communicate with a Restful API(running on localhost). My server is actually getting my Http requests but Visual Studio keeps throwing this error:
"The remote server returned an error: NotFound."
private void connect_tap(object sender, System.Windows.Input.GestureEventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.BeginGetResponse(GetResponseCallback, request);
}
void GetResponseCallback(IAsyncResult result)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
if (request != null)
{
WebResponse response = request.EndGetResponse(result);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string read = streamRead.ReadToEnd();
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(read);
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
});
streamResponse.Close();
streamRead.Close();
response.Close();
}
}
This is the full error:
{System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.b__d(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.b__0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at IonisSphere.Connect.GetResponseCallback(IAsyncResult result)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClass1d.b__1b(Object state2)}
The Web Exception occurs at the EndGetResponse() call. I removed the try/catch around to see the error but when it's there it always goes in the catch section and nothing happens.
I don't understand what is it not finding since my server gets my requests ...
It works fine with Postman by the way. I also tried with a POST method but got exactly the same result.
I'm stuck with this since a few days and I couldn't find anyhing helpful on the internet. I am quite new on Windows Phone and I know this is propably a stupid mistake but thanks in advance for the ones who will try to teach me =)
Related
I used ASP.NET to write a web page that accesses other websites to log in to the API, and it was successfully placed on my server, but when it was placed on the school's server to receive the token from the post, the following error was reported:
Server Error in '/classMeeting' Application. A connection attempt failed because the connecting party did not properly reply after a period of time or the connected host became unresponsive. 112.65.235.59:443
Description: An unhandled exception occurred during the execution of the current web request.
Please review the stack trace for more information about the error and where it originated in the code.
Exception Details:
System.Net.Sockets.SocketException:
A connection attempt failed because the connected party did not properly reply after a period of time or the connected host became unresponsive. 112.65.235.59:443
Source Error:
An unhandled exception was generated during the execution of the current webrequest. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +309
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) +633
System.Net.HttpWebRequest.GetRequestStream(TransportContext& context) +708
System.Net.HttpWebRequest.GetRequestStream() +21
classMeeting.index.GetAccess_token(String code, String client_id, String redirect_uri, String client_secret) in C:\Users\admin\source\repos\classMeeting\index.aspx.cs:130 classMeeting.index.readyLogin() in C:\Users\admin\source\repos\classMeeting\index.aspx.cs:32
classMeeting.index.Page_Load(Object sender, EventArgs e) in C:\Users\admin\source\repos\classMeeting\index.aspx.cs:25
System.Web.UI.Control.OnLoad(EventArgs e) +109
System.Web.UI.Control.LoadRecursive() +68
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3321
My source code is:
public static string GetAccess_token(string code, string client_id, string redirect_uri, string client_secret)
{
var url = "https://openapi.yiban.cn/oauth/access_token";
byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("client_id={0}&client_secret={1}&code={2}&redirect_uri={3}", client_id, client_secret, code, redirect_uri));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
webRequest.Method = "Post";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
ServicePointManager.DefaultConnectionLimit = 50;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.Default);
return php.ReadToEnd();
}
How should we do to fix this error?
If you get any error code like 10036 for a socket connection error then you can find the related error section from this link
Check the parameters you use for connection like hostname and port, and also make sure your firewall doesn't drop packages or block your connection.
The code you provided is correct, there are several reasons for this phenomenon:
Check whether the status of the server is abnormal. For example, there may be a state of not starting or being paralyzed.
Whether the status of your destination URL is normal. Whether there is an unreachable state.
Whether your server can access your target website. Due to the server's need for a secure environment, there are usually some URLs that cannot be accessed by the server. At this point you need to change your server port. If it still doesn't work, try sending and receiving web requests to hosts that it can access successfully.
I am working on a program that automatically queries a website every 5 seconds. It has been working fine for the last few days, but today when I simply restarted it, it keeps throwing System.ObjectDisposedException on the line marked underneath. I should mention that accessing this URL via a browser on the same machine works fine.
Code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.bitstamp.net/api/ticker/");
request.Method = "GET";
try
{
// ObjectDisposedException thrown here
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
string resultString = reader.ReadToEnd();
return resultString;
}
}
}
catch (WebException ex)
{
// Handle it
}
Stack Trace:
System.ObjectDisposedException occurred
_HResult=-2146232798
_message=Cannot access a disposed object.
HResult=-2146232798
IsTransient=false
Message=Cannot access a disposed object.
Object name: 'SslStream'.
Source=System
ObjectName=SslStream
StackTrace:
at System.Net.Security.SslState.ValidateCreateContext(Boolean isServer, String targetHost, SslProtocols enabledSslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, Boolean remoteCertRequired, Boolean checkCertRevocationStatus, Boolean checkCertName)
InnerException:
Is there something I am doing wrong? I do not even access the response stream before the using, how can it be disposed?
EDIT: Added url and stack trace
Simplifying things a bit and just doing a:
WebRequest.Create("https://www.bitstamp.net/api/ticker/").GetResponse();
I'm getting WebException "The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF", which apparently is indicative of a problem at the server end, and one (perhaps the only) way round it is to add the following to your config file:
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
</system.net>
Worked for me anyway.
Our console applications are making hundreds of WebRequests to Facebook every minute (with using multiple apps and hundreds of access tokens). Now, they started to fail with the exception message in the title ("The request was aborted: The request was canceled"). We searched for hours on the internet, and tried out every possible solution, but nothing helped.
These didn't help:
webRequest.Timeout = 20000; //A request that didn't get respond within 20 seconds is unacceptable, and we would rather just retry.
webRequest.KeepAlive = false;
webRequest.ProtocolVersion = HttpVersion.Version10;
webRequest.ServicePoint.Expect100Continue = false;
Anyone has any other idea?
edit:
ToString of the Exception: System.Net.WebException: The request was
aborted: The request was canceled. ---> System.Net.WebException: The
request was canceled at
System.Net.ServicePointManager.FindServicePoint(Uri address, IWebProxy
proxy, ProxyChain& chain, HttpAbortDelegate& abortDelegate, Int32&
abortState) at System.Net.HttpWebRequest.FindServicePoint(Boolean
forceFind) at
System.Net.HttpWebRequest.DoSubmitRequestProcessing(Exception&
exception) at System.Net.HttpWebRequest.SetResponse(Exception E) ---
End of inner exception stack trace --- at
System.Net.HttpWebRequest.GetResponse() at WebException message: The
request was aborted: The request was canceled.
edit2: And we are NOT reaching the limit. We know when that happens,
and the problem is NOT that. We have been doing this for two years,
and this thing only happened twice during the whole time. Per
AccessToken we are only doing 2-3 requests/minute, and the throttling
on Facebook is 600 requests/accesstoken/ip.
edit3: I would like to add an extra tip for people who have this or similar problem: Make sure that you dispose your RequestStream, your Response and your ResponseStream object.
http://www.dotnetframework.org/default.aspx/4#0/4#0/untmp/DEVDIV_TFS/Dev10/Releases/RTMRel/ndp/fx/src/Net/System/Net/ServicePointManager#cs/1305376/ServicePointManager#cs
I can see where the exception is thrown. Did you try increasing the HTTP request limit? The default is 2 per seconds.
ServicePointManager.DefaultConnectionLimit = 1000;
My Solve for Xamarin
public async Task<string> GetMessageEx(HttpWebResponse response)
{
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string result = await streamRead.ReadToEndAsync();
await streamResponse.FlushAsync();
return result;
}
I have been struggling the entire day to get my C# Windows Phone 8 to talk to my PHP web server over SSL (HTTPS). My server is implemented in such a way that it reads the GET parameters sent to it and then echos an appropriate response. It already works fine in the Windows Phone internet browser by going to https://sub.mysite.com/mypage.php?param=value but for the likes of me I cannot get it to work with my app.
Now I should mention that the server has a self-signed certificate which I have included with my application and at first start up I prompt the user to install the certificate using:
await Launcher.LaunchFileAsync(await Package.Current.InstalledLocation.GetFileAsync("server.cer"));
This seems to work fine because after the certificate is installed Internet Explorer on the device does not warn me about an uncertified certificate anymore.
The thing is though that trying to access the server via either WebClient or WebRequest both give me this error:
An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
'TaskHost.exe' (CLR C:\windows\system32\coreclr.dll: Silverlight AppDomain): Loaded 'C:\windows\system32\en-US\System.debug.resources.DLL'. Module was built without symbols.
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in System.ni.dll
An exception of type 'System.Reflection.TargetInvocationException' occurred in System.ni.dll and wasn't handled before a managed/native boundary
System.Reflection.TargetInvocationException: An exception occurred during the operation, making the result invalid. Check InnerException for exception details. ---> System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.ClientHttpWebRequest.<>c_DisplayClasse.b_d(Object sendState)
at System.Net.Browser.AsyncHelper.<>c_DisplayClass1.b_0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)
--- End of inner exception stack trace ---
at System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
at System.Net.DownloadStringCompletedEventArgs.get_Result()
at HttpsDing.MainPage.client_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
The implementation for both of them though work fine when accessing a normal site like http://bing.com or even https://bing.com.
The code for the webclient method is:
WebClient client = new WebClient();
client.DownloadStringAsync(new Uri("https://sub.mysite.com"));
client.DownloadStringCompleted += client_DownloadStringCompleted;
And the code for the webrequest is:
public static class Extensions
{
public static System.Threading.Tasks.Task<System.IO.Stream> GetRequestStreamAsync(this System.Net.WebRequest wr)
{
if (wr.ContentLength < 0)
{
throw new InvalidOperationException("The ContentLength property of the WebRequest must first be set to the length of the content to be written to the stream.");
}
return Task<System.IO.Stream>.Factory.FromAsync(wr.BeginGetRequestStream, wr.EndGetRequestStream, null);
}
public static System.Threading.Tasks.Task<System.Net.WebResponse> GetResponseAsync(this System.Net.WebRequest wr)
{
return Task<System.Net.WebResponse>.Factory.FromAsync(wr.BeginGetResponse, wr.EndGetResponse, null);
}
}
And then:
await AuthenticateAsync();
This is all rather confusing to me, any ideas?
I am new to accessing web services with Windows Phone 7/8. I'm using a WebClient to get a string from a php-website. The site returns a JSON string but at the moment I'm just trying to put it into a TextBox as a normal string just to test if the connection works.
The php-page requires an authentication and I think that's where my code is failing. Here's my code:
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("myUsername", "myPassword");
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri("https://www.mywebsite.com/ba/php/jsonstuff.php"));
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
string data = e.Result;
this.jsonText.Text = data;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
This returns first a WebException and then a TargetInvocationException. If I replace the Uri with for example "http://www.google.com/index.html" the jsonText TextBox gets filled with html text from Google (oddly enough, this also works even when the WebClient credentials are still set).
So is the problem in the setting of the credentials? I couldn't find any good results when searching for guides on how to access php-pages with credentials, only without them. Then I found a short mention somewhere to use the WebClient.Credentials property. But should it work some other way?
Update: here's what I can get out of the WebException (sorry for the bad formatting):
System.Net.WebException: The remote server returned an error: NotFound. --->System.Net.WebException: The remote server returned an error: NotFound.
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.ClientHttpWebRequest.<>c_DisplayClasse.b_d(Object sendState)
at System.Net.Browser.AsyncHelper.<>c_DisplayClass1.b_0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)
Update 2: Here's the error log line:
Nov 16 17:51:12 myservice httpd[21036]: 127.0.0.1 - - [16/Nov/2012:17:51:12 +0200] "GET /ba/php/jsonstuff.php?origpath=/ba/php/jsonstuff.php HTTP/1.1" 401 290 "-" "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"
401 I guess would suggest false credentials?
In my opininion you really need to see how the server handles your request. "NotFound" in WebException could mean that you're referring to a location that doesn't exist. But I'm sure that you pass the right URL. So there must be some logic on the server that redirects you.
If you go to the url using your desktop browser - do you have any kind of SSL certificate error or warning? Maybe that's the reason. Try navigating on your phone using IE.
Or you could set up another host just to give it a try.
I'll set up a host on my machine and try it.
The problem is with the SSL certificate I guess. WP is very strict when it goes to checking SSL certificates, so you should try without ssl or install cert on your emulator/phone or install valid (not self generated) cert on your server.
Okay, so I found a way to get this working. The problem was that the WebClient class couldn't properly handle the cookies of the web service.
After some Google searches I found this solution and it works perfectly:
http://firebelly.net/post/3341374382/cookie-aware-webclient-for-wp7
So basically you just make your own client class that extends the WebClient class which can store cookies.