Windows Phone 8.1 print result of an HTTP request - c#

I can not print or process the data that I receive after making an HTTP request.
This is the code I wrote:
private void Button_Click(object sender, RoutedEventArgs e)
{
String jsonUri = "hxxp://xxxxx/zzzz/yyyyyy; //censured
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(jsonUri);
request.BeginGetResponse(GetDataCallback, request);
}
void GetDataCallback(IAsyncResult result)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
if (request != null)
{
WebResponse response = request.EndGetResponse(result);
testo.Text = response.GetResponseStream().ToString();
}
}
I tried various solutions but I just can not print the result.
apache I see the call, and the data from the app I could see that coming

Related

IIS asp.net C# API Post Method error "'The remote server returned an error: (403) Forbidden.'"

I have via gupshup created a viber bot. I run my WebForm application with IIS server in win 10. I tried to send a message to my viberbot via api post method but c# strangle me.(I tested url and parameters with success)
here is my code :
protected void viber_msg(String viberid, String strmsg)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.gupshup.io/sm/api/bot/mybotname/msg?apikey=mykey");
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "context={'botname':'mybotname','channeltype':'viber','contextid':'viberid','contexttype':'p2p'}&message="+strmsg;
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
viber_msg("viberuserID", "This is a message");
}
The error I am getting is "System.Net.WebException: 'The remote server returned an error: (403) Forbidden.'"
Also tried with POSTMAN and getting "message": "Invalid authentication credentials"
Thnx in advance...
protected void viber_msg(String viberid, String message)
{
var client = new RestClient("https://api.gupshup.io/sm/api/bot/mybot/msg?apikey=myapikey");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("context", "{\"botname\": \"mybot\",\"channeltype\" :\"viber\",\"contextid\": \""+viberid+"\",\"contexttype\": \"p2p\"}");
request.AddParameter("message", message);
IRestResponse response = client.Execute(request);
}
protected void Button1_Click(object sender, EventArgs e)
{
viber_msg("viberid", "message");
}
}
RestSharp Library!!!

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.

HTTP Request Not found error windows phone

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.

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.

Categories