I'm building an app with Xamarin Forms. I have no issues with Android, but when I attempt to simulate or deploy the iOS app, my HttpClient can't seem to connect to the server. After the timeout expires, I get a TaskCanceledException.
The HttpClient is actually used in a separate project that is referenced by the iOS app, if that matters. Here's my usage:
string serviceUri = service + methodName;
HttpRequestMessage request = new HttpRequestMessage(methodRequestType, serviceUri)
{
Content = new StringContent(content, Encoding.UTF8, "application/json")
};
HttpResponseMessage response = await _client.SendAsync(request).ConfigureAwait(false);
string returnString = await response.Content.ReadAsStringAsync();
return returnString;
I'm not using any waits or accessing .Result, as I've seen many people try that don't understand async operations.
I've seen older posts (circa 2013) where the wrong HttpClient is used. Is this still an issue in current releases? I've also tried changing the HttpClient implementation in the iOS project settings, to no avail.
Thanks in advance!
The issue was an invalid Deployment Target - It was set to "80" instead of "8.0
In come cases, the build server does not communicate this invalidity back to your machine - hence why it took so long to notice it!
Related
I'm in the testing phase of my first Xamarin.Forms app, which relies heavily on the HttpClient to retrieve JSON data from a remote site. I've found that once a request has been made, the response seems to be cached and updated data is never retrieved. I'm initializing the HttpClient like this:
new HttpClient()
{
Timeout = new TimeSpan(0, 0, 1, 0),
DefaultRequestHeaders =
{
CacheControl = CacheControlHeaderValue.Parse("no-cache, no-store, must-revalidate"),
Pragma = { NameValueHeaderValue.Parse("no-cache")}
}
}
Those request headers didn't seem to help at all. If I put one of the URLs in my browser, I get the JSON response with the updated data. The server side is setting a no-cache header as well.
Any idea how I can FORCE a fresh request each time? TIA. This testing is being done in an Android emulator, btw. I don't know yet whether the iOS build is behaving similarly.
I'd suggest you use the modernhttpclient nuget package, and implement your android code like:
var httpClient = new HttpClient(new NativeMessageHandler());
This code works on both android, iOS and/or code in a PCL. Basically this nuget package makes sure that you are using the latest platform optimizations for the HttpClient. For Android this is the OkHttp-package, for iOS this is NSURLSession.
This helps you prevent any of the quirks of the provided HttpClient class, and use the optimizations that the platform you're running offers you.
Issues like the one you show should no longer happen.
I'm trying to make a simple web api call using HttpClient in an iOS build. When setting the client.BaseAddress, the BaseAddress always ends up null. I can't find what could possibly be wrong.
using System.Net.Http;
....
private const string BaseApiUrl = "http://localhost:55904/";
static HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BaseApiUrl);
// client.BaseAddress is still null
I downloaded a sample non-Xamarin project and the same code works fine.
Any ideas?
Update
As I continue messing with this I figured I would try some of the other platforms. UWP seems to work fine. I was going to test Android but all of a sudden, I have a bunch of "The name 'InitializeComponent' does not exist in the current context" errors.
I'm new to Xamarin but not to VS or C#.
Update
I was just thinking, does iOS need to request any special permission for internet access? If so, where would that be set?
Just in case anyone else comes across this problem, I found the cause. It turns out that the iOS project didn't include a reference to System.Net.Http. Once I added the reference, everything worked fine.
So I've been working on a xamarin PCL project targeting android and windows store app and I've had this issue for about two weeks now. One of the very first things this app does is to make an http request to a yahoo service when the user tries to search for something.
Now, on the windows store app project, this works just fine. However, whenever I'm debugging the android project, this fails miserably. It times out and I get a TaskAbortedException.
I've navigated with the browser within the android emulator to the restful service url and I do get a response in the browser but nothing when I make the http request. I have tried everything I could think of but no cigar. I have researched this for weeks now and I have yet to find an answer. It should be noted that I'm making the request within the PCL project with HttpClient.
Here's the code where this happens:
var queryUrl = string.Format(QUERY_URL_TEMPLATE, TickerSearch);
try
{
var requestTask = httpClient.GetStringAsync(queryUrl);
requestTask.ContinueWith(t =>
{
var responseDto = JsonConvert.DeserializeObject<TickerSearchResultDto>(t.Result);
TickerSearchResults = responseDto.ResultSet.Result;
});
}
catch (Exception ex)
{
}
Any help is greatly appreciated.
I am building an app which is already build in Android & other Mobile Platform. Since the App uses REST based Webservices build in JAVA, thus I need to use these Webservice URL. The code uses HttpClient and HttpGet for GET,POST,PUT & DELETE operation in Android . Can anyone guide me where to start with as I am new to this Platform.
You can use HttpWebRequest ( http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(v=vs.95).aspx ) to make calls to a REST service
I would recommend using the WebClient class for simple HTTP based communication. Here is the basic format I typically use when making a request to a web service:
WebClient web = new WebClient();
web.OpenReadCompleted += new OpenReadCompletedEventHandler(RequestComplete);
web.OpenReadAsync(new Uri("http://fullurlofyourwebservice.com"));
You can then write a method for the RequestComplete method referenced in the second line of code:
void RequestComplete(object sender, OpenReadCompletedEventArgs e)
{
string response = "";
using (var reader = new StreamReader(e.Result))
{
response = reader.ReadToEnd();
}
}
You can then process the response as a simple string, or do something like XDocument.Parse(response) if your response is in XML format.
Check out the full MSDN documentation for a complete reference.
I've recently started using RestSharp. http://restsharp.org/
Small, simple and does what it says on the box.
I am writing an android app that makes requests using the HttpClient interface from the Apache Commons project (supplied with both versions of android).
The problem occurs in the following code listing:
try {
URI uri = URIUtils.createURI(SCHEME, host, DEFAULT_PORT, QUERY,
URLEncodedUtils.format(qparams, ENCODING), EMPTY_FRAGMENT);
HttpUriRequest request = new HttpGet(uri);
response = client.execute(request);
} catch (Exception e) {
throw new CheckedSecurityException("Could not execute request", e);
}
Android 2.2 does this just fine (API level 8) but when I run this on Android 2.1-update1 (API level 7) it "hangs" at client.execute(request). What am I doing wrong?
Okay, I figured this out myself.
Part of the problem was that I had to use 10.0.2.2 from the emulator and I wrote a class that detects the emulator using the model. the string google_sdk worked fine for me before. But yesterday I updated my SDK and apparently they changed it to just sdk so the class wasn't detecting the device as an emulator before and was using the wrong IP address.
Status: Solved!