I am trying to call a WCF service from a windows phone 8.1 app, the option to add a service reference no longer exists.
I tried this:
HttpClient httpClient = new System.Net.Http.HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://serverURl/serviceName.svc/methodName?variableName=value");
HttpResponseMessage response = await httpClient.SendAsync(request);
string data = await response.Content.ReadAsStringAsync();
But it didnt work, the string is always empty.
N.B The server is also not local host so im not facing the problem of connecting from windows phone emulator to local host.
Try this.
If its not working, let me know.
HttpClient httpClient = new System.Net.Http.HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,"http://localhost:18362/Service1.svc/GetData");
HttpResponseMessage response = await httpClient.SendAsync(request);
string data = await response.Content.ReadAsStringAsync();
var dialog = new MessageDialog(data);
await dialog.ShowAsync();
Windows Phone Store apps in Windows Phone 8.1 do not support the System.ServiceModel namespace.
There is a workaround you can
Read here.
You can use System.Net.Http :
public async Task<string> GetMethod(string url)
{
HttpClient client = new HttpClient();
var response = await client.GetAsync(url); // The Get Process to get result from WCF service
string result = await response.Content.ReadAsStringAsync(); // Get Json string result
return result;
}
}
Related
If I make a web service request and background the iOS app and foreground it again, I get an exception that the request has been canceled. Is this a bug or the way iOS operates? I can't find any documentation on this. What's the right way to implement a reliable web service mechanism using Xamarin Forms? I followed the HttpClient example as documented here.
This works for me both in the foreground and in the background.
maybe you also need to enable background modes in your info.plist
private async Task<string> UsaHttpClient()
do
{
...
...
...
await Task.Run(async () =>
{
HttpClient Client = new HttpClient();
Client.BaseAddress = new Uri("https://services.xxxxx.com/ServiceApi/");
var response = Client.GetStringAsync("api/function?Parametro...").Result;
HttpResponseMessage resp = new HttpResponseMessage();
resp.Content = new StringContent(response, Encoding.UTF8, "application/json");
r = response;
resp.Dispose();
Client.Dispose();
await Task.Delay(second for delay);
});
} while (X == anyCondition);
}
I have a WebAPI service running on a server, and I am able to hit against it all day long in an MVC app I have. I am now trying to create an Xamarin Android app that also hits against the same WebAPI. I put together some code in a console app to test, and it works just fine. However, when I put the same code in my Xamarin Android app, it cannot connect to the service, I get back an aggregate exception that basically wraps a WebException. Digging into the exception further, it seems it is a System.Net.WebExceptionStatus.ConnectFailure type of error.
Here is the code:
using (HttpClient webAPI = new HttpClient())
{
// hardcode the request to try and see why it errors
AuthUserRequest thisUser = new AuthUserRequest
{
UserName = "username",
Password = "password",
AppName = "Dashboard"
};
webAPI.MaxResponseContentBufferSize = 256000;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(thisUser);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response;
try
{
response = await webAPI.PostAsync("It'sOurURL", content);
}
catch (Exception err)
{
string sHold = err.Message;
throw;
}
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
Context thisContext = Application.Context;
Toast toast = Toast.MakeText(thisContext, "Successful", ToastLength.Short);
toast.Show();
}
}
As I said it's weird it works just fine from a Console app, just not the Xamarin Android app. Any insight at all into this?
All looks pretty good. My API calls are working in Xamarin Android and iOS. My code is pretty much the same with two real minor differences. I have set ConfigureAwait(false) on the PostAsync call. Additionally I have created a URI variable with the address for the API endpoint and passed that into the PostAsync method, rather then using a hard coded string.
using (var client = new HttpClient())
{
var user = new CredentialsModel
{
Password = password,
Username = username,
};
var uri = new Uri("YOUR_URL_GOES_HERE");
var json = JsonConvert.SerializeObject(user);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(uri, content).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
var authData = JsonConvert.DeserializeObject<ResponseModel>(responseContent);
return authData;
}
return null;
}
It was my own bone-headed mistake... When I tried the URL this morning, it was there, but the IT department has been mucking about with the server, so it's no longer available externally. Sorry to bother everyone with this.
I am developig a windows app 8.1. Where I am calling an json api in a page say "Page1". My issue is that when I navigate to another page say "Page2" and come back to "Page1", I recive the same data from the api. I found that when I come back to the Page1 again, my web api is called but the result is come from I guess from cache.So, json data is not updated. How can I overcome with this issue. Any suggestion is most welcome.
My Rest API Call Code Is
var client = new HttpClient(); // Add: using System.Net.Http;
var response = await client.GetAsync(new Uri(url));
response.Headers.Add("Cache-Control", "no-cache");
var result = await response.Content.ReadAsStringAsync();
response.Dispose();
client.Dispose();
return ressult.
In the calling url just add a random parameters like
string uri = string.format(http://www.myservice.com?time={0}",DateTime.Now);
var response = await client.GetAsync(new Uri(uri));
I am trying to access a html page to scrape data from my Windows Phone 8. But first i need to send log-in credentials to it. I am currently using htmlAgilityPack to scrape the data from the login page. I have tried to use WebBrowser instance to run in the background, but the html page is not automatically clickable and i cannot proceed. After which i tried to use the HttpClient class to send data using PostAsync() method, which only recieves a HttpResponseMessage, with which i have no clue what to do, but i am successfully able to send the credential data using a HttpContent object.
var httpResponseMessage = await client1.PostAsync("https://www.webpage.com", content);
After that i have been massively unsuccessful in progressing forward.
Thank you in advance for any help.
Here's how I use HttpClient class to communicate with a webservice in my project:
public async Task<string> httpPOST(string url, FormUrlEncodedContent content)
{
var httpClient = new HttpClient(new HttpClientHandler());
string resp = "";
HttpResponseMessage response = new HttpResponseMessage();
response = await httpClient.PostAsync(url, content);
try
{
response.EnsureSuccessStatusCode();
Task<string> getStringAsync = response.Content.ReadAsStringAsync();
resp = await getStringAsync;
}
catch (HttpRequestException)
{
resp = "NO_INTERNET";
}
return resp;
}
Here you can see how to retrieve the data. Hope it helps :)
I want to get source code of some website.
I found this solution:
var html = System.Net.WebClient().DownloadString(siteUrl);
But VisualStudio tells that WebClient does not exist in System.Net.
How to fix that? Or how to do it other way?
PS: does windows phone have some special tag which developers usually use when they looking for some code/solutions?
WebClient does exist in WP8 like this:
WebClient thisclient = new WebClient();
thisclent.DownloadStringAsync(new Uri("urihere");
thisclient.DownloadStringCompleted += (s, x) =>
{
if (x.Error != null)
{
//Catch any errors
}
//Run Code
}
For 8.1 apps, use something like this:
HttpClient http = new System.Net.Http.HttpClient();
HttpResponseMessage response = await http.GetAsync("somesite");
webresponse = await response.Content.ReadAsStringAsync();
WebClient is available for Windows Phone Silverlight 8.1 apps.
Windows Phone Runtime apps use Windows.Web.Http.HttpClient.
There is also a Portable HttpClient for .NET Framework and Windows Phone.
This is what I currently use to download HTML source from webpages:
public static async Task<string> DownloadPageAsync(string pageURL)
{
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
return result;
}
}
This function will return downloaded html of pageURL.