HTTP Request Not found error windows phone - c#

I have a HTML page hosted on a local Apache server and I'm trying to make a HTTP web request to the page using the below code. The code runs into a web exception, and throws an invalid argument exception too. This happens in the piece of code used to get the data from the stream in the catch section of the code:
private void b1_Click_1(object sender, RoutedEventArgs e)
{
System.Uri targetUri = new System.Uri(#"http://192.168.1.4/san/index1.html");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUri);
request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);
}
private void ReadWebRequestCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
try
{
HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);
using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
{
string results = httpwebStreamReader.ReadToEnd();
//TextBlockResults.Text = results; //-- on another thread!
// Dispatcher.BeginInvoke(() => TextBlockResults.Text = results);
}
myResponse.Close();
}
catch (WebException ex)
{
using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
{
Debug.WriteLine(reader.ReadToEnd());
}
}
}

Are you trying to access the page from the emulator or the device? If it's the device, you need to make sure that the web page is accessible from a secondary device. That is - make sure that port 80 is open for LAN access.

Related

How to use eucalyptus REST api in c#

Could anyone help me with this example of REST api “describe eucalyptus instances” in c# without using AWS sdk for .net?
I give you my sample code. This code is running in aws successfully, but in eucalyptus they give a “404 not found” error.
protected void Page_Load(object sender, EventArgs e)
{
EucaListInstance("xyx/services/Eucalyptus");
}
private void ListEucaInstance(string inboundQueueUrl)
{
// Create a request for the URL.
string date = System.DateTime.UtcNow.ToString("s");
string stringToSign = string.Format("DescribeInstances" + date);
string signature = CalculateEucaSignature(stringToSign, true);
StringBuilder sb = new StringBuilder();
sb.Append(inboundQueueUrl);
sb.Append("?Action=DescribeInstances");
sb.Append("&Version=2013-10-15");
sb.AppendFormat("&AWSAccessKeyId={0}", m_EucaAccessKeyID);
sb.AppendFormat("&Expires={0}", date);
sb.AppendFormat("&Signature={0}", signature);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sb.ToString());
HttpWebResponse response = null;
Stream dataStream = null;
StreamReader reader = null;
try
{
request.Credentials = CredentialCache.DefaultCredentials;
response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
reader = new StreamReader(dataStream);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Cleanup the streams and the response.
if (reader != null)
reader.Close();
if (dataStream != null)
dataStream.Close();
if (response != null)
response.Close();
}
}
private string CalculateEucaSignature(string data, bool urlEncode)
{
ASCIIEncoding ae = new ASCIIEncoding();
HMACSHA1 signature = new HMACSHA1(ae.GetBytes(m_EucaSecretKey));
string retSignature = Convert.ToBase64String(signature.ComputeHash(ae.GetBytes(data.ToCharArray())));
return urlEncode ? HttpUtility.UrlEncode(retSignature) : retSignature;
}
You would get a 404 error if you are sending the request to the wrong URL. I would verify that you are sending to the correct URL, which would typically be along the lines of:
http://eucalyptus.your.domain.here.example.com:8773/services/Eucalyptus
You can find the URL to use in your deployment by looking in your eucarc file for the EC2_URL value, or by running the "euca-describe-services -T eucalyptus" admin command (in versions up to 4.0, for 4.0 onward you would use "-T compute")

Windows Phone 8: passing data from PHP page to windows phone 8 app

I need to send some data from php page to windows phone 8(C#) and need to display it.
Here is my wp8 side Code :
private void Track_Click(object sender, RoutedEventArgs e)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(attackUri);
request.BeginGetResponse(Showtext, request);
}
}
void Showtext(IAsyncResult result)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
if (request != null)
{
try
{
WebResponse response = request.EndGetResponse(result);
var txt = request.Content.ReadAsStringAsync();
//to display data passed from PHP page
MessageBox.Show(txt.Result);
}
catch (WebException e)
{
}
}
}
I'm not quite sure, where you got your request.Content from, but it does not seem to be WP8 native.
Try the following. This is how it always worked for me:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://www.google.de"));
request.BeginGetResponse(ShowText, request);
private void ShowText(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
string content = streamReader.ReadToEnd();
Debug.WriteLine(content);
}
}

Trouble in fetching results from server in windows phone

I'm communicating with my server with the following code,
private void Save_Click(object sender, RoutedEventArgs e)
{
var request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.BeginGetResponse(new AsyncCallback(GotResponse), request);
}
private void GotResponse(IAsyncResult asynchronousResult)
{
try
{
string data;
HttpWebRequest myrequest = (HttpWebRequest)asynchronousResult.AsyncState;
using (HttpWebResponse response = (HttpWebResponse)myrequest.EndGetResponse(asynchronousResult))
{
System.IO.Stream responseStream = response.GetResponseStream();
using (var reader = new System.IO.StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
}
this.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(data);
});
}
catch (Exception e)
{
var we = e.InnerException as WebException;
if (we != null)
{
var resp = we.Response as HttpWebResponse;
var code = resp.StatusCode;
this.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Message :" + we.Message + " Status : " + we.Status);
});
}
else
throw;
}
}
I'm giving date and amount as my input value,it is url encoded. If all my data's are valid then everything works fine. And so my server will give the data as
{
"code":0,
"message":"Success",
"data":{
"date":xxxx,
"amount":123
}
}
But in case if give an invalid value,(For eg: abcd for 'amount'), then my server would reply as
{
"code":2,
"message":"Invalid value passed"
}
In this case, after Executing the line
using (HttpWebResponse response = (HttpWebResponse)myrequest.EndGetResponse(asynchronousResult))
It jumps to catch, and it display
Message:The remote server returned an error:NotFound. Status:UnKnown Error
Required Solution: It should fetch the result as it did in the previous case.
What sholud i do to fix it?
Well presumably the HTTP status code is 404. You're already accessing the response in your error code though - all you need to do is try to parse it as JSON, just as you are in the success case, instead of using we.Message to show an error message. You should probably be ready for the content to either be empty or not include valid JSON though, and only do this on specific status codes that you expect to still return JSON.

App hangs when not being debugged in Visual Studio

I have this app which authenticates a user with external web service and should navigate to a different view once authenticated.
The authentication is done in a HttpWebRequest:
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create("http://webservice");
request.Method = "GET";
request.BeginGetResponse(new AsyncCallback(CheckLogin), request);
}
Then here is the callback:
private void CheckLogin(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
bool success = false;
try
{
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
if (responseString.Contains("ok"))
{
success = true;
}
streamResponse.Dispose();
streamRead.Dispose();
response.Dispose();
}
catch (Exception e)
{
}
request.Abort();
request = null;
if (success)
{
this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
Frame.Navigate(typeof(Main2));
}).AsTask().Wait();
}
}
This is working perfectly when debugging in Visual Studio but when I have published the application and installed the package, it hangs on Frame.Navigate. I guess this is because the CheckLogin method is not running in the UI thread.
Any ideas on how to Frame.Navigate(..) in a background thread?
It seems to be no real problems between Dispatcher.RunAsync and Frame.Navigate. So I assume you're not looking in the right direction.
Maybe your page's content is faulty, instead of the navigation.

checking if url is up and working, if it is to redirect to that url itself else if not working to redirect to another url

namespace WebApplication4
{
public partial class _Default : System.Web.UI.Page
{
public static bool UrlIsValid(string url)
{
bool br = false;
try
{
IPHostEntry ipHost = Dns.Resolve(url);
br = true;
}
catch (SocketException)
{
br = false;
}
return br;
}
private void Page_Load(object sender, EventArgs e)
{
string url = "http://www.srv123.com";
WebRequest wr = WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)wr.GetResponse ())
{
if (response.StatusCode == HttpStatusCode.OK)
{
response.Close();
Response.Redirect(url);
}
else
{
Response.Redirect("http://www.yahoo.com");
}
when i give google it redirects to google but when i giv an invalid url it doesn redirect to yahoo lik hw i hav given. i gave the response before redirect
Your UrlIsValid takes a parameter called smtpHost, suggesting it works with SMTP mail servers. Then within it, you attempt to resolve the entire URL as a hostname. It simply won't work at all.
You could create a new Uri object with the URL in, then create a WebRequest object, see the example here:
http://msdn.microsoft.com/en-us/library/system.uri.aspx
Uri siteUri = new Uri("http://www.contoso.com/");
WebRequest wr = WebRequest.Create(siteUri);
// now, request the URL from the server, to check it is valid and works
using (HttpWebResponse response = (HttpWebResponse)wr.GetResponse ())
{
if (response.StatusCode == HttpStatusCode.OK)
{
// if the code execution gets here, the URL is valid and is up/works
}
response.Close();
}
Hope that helps!

Categories