Titanium HTTPClient doesn't send POST params on android - android

I try the following request in Titanium
var xhr = Titanium.Network.createHTTPClient();
xhr.open("POST", "http://www.example.com");
var params = {
username = "username",
password = "password"
};
xhr.send(params);
The problem is that it works in iPhone Simulator, but not on the android emulator/device
The request comes through to the server, but if I print the params in my php page, they are both empty.

Some webservers need the content type set or they don't pull out the parameters. Have you tried sniffing the header and contents of the Android traffic through proxy server?
var xhr = Titanium.Network.createHTTPClient();
xhr.open("POST", "http://www.example.com");
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var params = {
username = "username",
password = "password"
};
xhr.send(params);

This works for me I'm using Lift. Maybe your server doesn't handle it well.

Related

XF 504 on Get request when using Android HttpClient implementation

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
}

Connecting SQL Server database and Xamarin Android using Web API

localhost is not working, I am using a SQL Server database now, but I don't know what to put in localhost IP, I tried 10.0.2.2 and my ipv4 ip. it doesn't work too.
HttpClient client = new HttpClient();
string url = $"https://localhost:xxxxx/api/Feedback?email={feedback.Email}&subject={feedback.Subject}&message={feedback.Message}";
Exception
System.Net.WebException: 'Failed to connect to localhost/127.0.0.1:44330'
Code:
btnSend.Click += async delegate
{
Feedback feedback = new Feedback();
feedback.Email = edtEmail.Text;
feedback.Subject = edtSubject.Text;
feedback.Message = edtMessage.Text;
HttpClient client = new HttpClient();
string url = $"https://localhost:xxxxxx/api/Feedback?email={feedback.Email}&subject={feedback.Subject}&message={feedback.Message}";
var uri = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response;
var json = JsonConvert.SerializeObject(feedback);
var content = new StringContent(json, Encoding.UTF8, "application/json");
response = await client.PostAsync(uri, content);
Clear();
if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
{
Toast.MakeText(this, "Your Feedback is Saved ", ToastLength.Long).Show();
}
else
{
Toast.MakeText(this, "Your Feedback is not Saved", ToastLength.Long).Show();
}
};
}
Image of WebAPI:
Contents of WebAPI
It Depends on your Dev environment setup, if you are using a real phone then you have to make sure that your PC and your phone are on the same network and the corresponding port number is open in your PC firewall elsewhere the phone can't reach the service.

WebView Post on Android (preferably Xamarin)

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);
}

Post request does not work on android device

I've a Ionic v3 application, and when I build it on a android device, all the Http GET request work, but when a POST request is launch, I've got a CORS error...
That's my request:
//Headers
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
//Post data
let post_data = {
my_body: blabla
};
this.http.post(ENV.API_URL + 'test/test', post_data, {headers: headers}).subscribe((data: any) => {
})
If anyone can help me?

Null response while making a POST request using HttpClient from android Xamarin

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.

Categories

Resources