In my Xamarin Forms app I have a very basic GET request that results in a 504 'Method not allowed' on Android.
This is the controller that I am calling:
[AllowAnonymous]
[HttpGet]
[Route("api/system/backendversion")]
public int GetBackendVersion()
{
return 20200924;
}
This is the code that performs the request
var _client = new HttpClient();
var content = new StringContent(json, Encoding.UTF8, "application/json");
var httpRequest = new HttpRequestMessage(httpMethod, url)
{
Content = content,
Version = HttpVersion.Version10
};
var response = await _client.SendAsync(httpRequest);
The problem disappears when I change the HttpClient implementation from "Android" to "Managed".
Also the webrequest works fine in the XF.UWP version of my app.
I believe I put it on Android for a reason, but I'm unsure what the reason was (probably speed). I'm curious what goes wrong here.
Apperantly it breaks because the content (header?) is set to json when there is no json.
I fixed it like this:
var httpRequest = new HttpRequestMessage(httpMethod, url)
{
Version = HttpVersion.Version10
};
if (!string.IsNullOrWhiteSpace(json))
{
httpRequest.Content = new StringContent(json, Encoding.UTF8, "application/json");
}
var response = await _client.SendAsync(httpRequest);
this error is similar to iOS where you get an error if you put json body in a get request
if (httpMethod == HttpMethod.Get && !string.IsNullOrWhiteSpace(json))
{
Debugger.Break();//a get request with a body is not allowed on iOS and results in a error https://stackoverflow.com/questions/56955595/1103-error-domain-nsurlerrordomain-code-1103-resource-exceeds-maximum-size-i
}
Related
I'm trying to receive the response on a http post but the response comes empty. I know its something basic but i can't make it work.
It should receive a JSON with some data, but the data doesn't come, probably its a problem on the reply part on my code.
Heres the code:
Future<void> _login2() async {
HttpClient client = new HttpClient();
client.badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
String url = 'https://sistema.hutransportes.com.br/api/login.php';
Map map = {"user": "test", "pass": "123456"};
HttpClientRequest request = await client.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(map)));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply); //should show the data from the http
}
I would recommend you to use the powerful library https://pub.dev/packages/dio
Trying to post to a web view in Android. I need to pass in headers (username, password, contentType) AND body parameters. Currently I see webView.LoadUrl takes in the url and headers however I do not see any options for loading a url with body and headers. Just for reference Im trying to achieve something similar to this, which works perfectly in iOS:
public void OpenWebPage(ReviewWebRequest request)
{
var nsRequest = new NSMutableUrlRequest
{
Url = new NSUrl(request.Url),
HttpMethod = request.Method
};
var nsHeaders = request.Headers;
nsRequest.Headers = NSDictionary.FromObjectsAndKeys(nsHeaders.Values.ToArray(), nsHeaders.Keys.ToArray());
nsRequest.Body = NSData.FromString(request.BodyString, NSStringEncoding.UTF8);
webView.LoadRequest(nsRequest);
}
I have a webapi that i want to post json to and then return json. Im using xamarin to create my android app but it doesn't seem to support PostAsJsonAsync method for the httpclient. So im now trying PostAsync method that post httpcontent. So what i want to do is convert my json to so that it is of format httpcontent and json so that i can post it to my webapi. This is my code:
var clientRequest = new ResourceByNameRequest
{
Name = "G60",
UserId = "1"
};
var param = JsonConvert.SerializeObject(clientRequest);
HttpContent content = new StringContent(param, Encoding.UTF8, "application/json");
var client = new HttpClient();
var cancellationToken = new CancellationToken();
var result = client.PostAsync("https://mctwebapi-test.entrematic.com/api/Resource/ResourceByName?", content, cancellationToken).Result;
return reslist;
this just runs till the timeout. I can't figure out why it doesn't work. If you have any other suggestions on how to post json to webapi using Xamarin im more than happy to try that out!
Plz help!
I'm using a REST API to access PassSlot in an attempt to generate a pass / coupon. It seems that when i run the program i get the error: "Error: NameResolutionFailure".
I have:
public static async Task<string> SendAndReceiveJsonRequest()
{
string responseStr = null;
string uri = "https://api.passslot.com/v1/templates/my-template-ID/pass";
// Create a json string with a single key/value pair.
var json = new JObject (new JProperty ("lastName", lastName),
new JProperty ("firstName", firstName),
new JProperty ("percentOff", percentOff),
new JProperty ("offerDescription", offerDescription),
new JProperty ("entityName", entityName),
new JProperty ("expiry", expiry));
//Console.WriteLine ("Jake's JSON " + json.ToString ());
using (var httpClient = new HttpClient ())
{
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("My-Key-Here-xxx-xxx-xxx");
//create the http request content
HttpContent content = new StringContent(json.ToString());
try
{
// Send the json to the server using POST
Task<HttpResponseMessage> getResponse = httpClient.PostAsync(uri, content);
// Wait for the response and read it to a string var
HttpResponseMessage response = await getResponse;
responseStr = await response.Content.ReadAsStringAsync();
}
catch (Exception e)
{
Console.WriteLine("Error communicating with the server: " + e.Message);
}
}
return responseStr;
}
I'm running this on Android 4.4 via a Nexus 4. I'm on 3G (not wifi).
Any hints as to what might be happening here and why i'm getting the error.
In case the url request is in local network, Check if you url ip is set in the hosts device (the hosts setting of the smartphone, tablet, whatever you are using to test)
PD.
To edit the hosts setting device in android you may use this app
https://play.google.com/store/apps/details?id=com.nilhcem.hostseditor
Iam sending a POST request from my android app using Xamarin. Iam using HttpClient to make the request
Things I have done:
1) Specified Internet permission
2) Tested the request from Postman for google Chrome
3) Debugged the code step by step
Problem:
1) I get the response as null.
2) Found the issue might be while receiving the response.
Here is my code:-
var resultString = String.Empty;
var registerContent = new StringBuilder();
registerContent.Append("DeviceId=");
registerContent.Append(deviceId);
registerContent.Append("&");
registerContent.Append("Name=");
registerContent.Append(deviceName);
registerContent.Append("&");
registerContent.Append("EncodedAccountNameā€¸=");
registerContent.Append(username);
var client = DataClient.Instance;
var request = new HttpRequestMessage(HttpMethod.Post,new Uri(EndPoints.RegisterDeviceEndPoint, UriKind.Absolute))
{
Content = new StringContent("DeviceId=" + deviceId + "&Name=" + deviceName + "&EncodedAccountName=" + username)
};
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var result = await client.SendAsync(request);
if (result.StatusCode == HttpStatusCode.OK)
{
resultString = HostUrl.GeAuthorizationtResult(result.Content.ReadAsStringAsync().Result);
}
return resultString;
Any help is appreciated
Thanks
It looks like you have a lot of app-specific code in there, so it's difficult to say what's causing the issue. You can simplify your code by using HttpClient's built-in support for form posts.
var httpClient = new HttpClient();
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("DeviceId", deviceId),
new KeyValuePair<string, string>("Name", deviceName),
new KeyValuePair<string, string>("EncodedAccountName", username)
};
var response = await httpClient.PostAsync(requestUrl, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
var resultString = await response.Content.ReadAsStringAsync();
Try this and see if it solves the issue. Otherwise, you'll need to expand on what HostUrl.GeAuthorizationtResult() does.