Response content of HttpResponseMessage on making a Post request is always '{}' in uwp - c#

I am making HTTP Post call to a webservice url. In the response I get 200 Status Ok message. But when I try to get the response content using await response.Content.ReadAsStringAsync() its always '{}'. The web service returns either SUCCESS or FAILED based on the user credentials passed. How do I retrieve the message. Please help.
Code to make a web service call
public Task<HttpResponseMessage> PostAsJsonAsync<T>(Uri uri, T item)
{
var client = new HttpClient();
var itemAsJson = JsonConvert.SerializeObject(item);
var content = new StringContent(itemAsJson);
//var content = new FormUrlEncodedContent(itemAsJson);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Clear();
return client.PostAsync(uri, content);
}
private async void mainPage_Loaded(object sender, RoutedEventArgs e)
{
UserDetails details = new UserDetails()
{
username = composite["username"].ToString(),
userpass = composite["password"].ToString()
};
var response = await PostAsJsonAsync(new Uri("http://ec2-xxxx-.compute-1.amazonaws.com:8080/Sanjeevani/rest/SV/login"), details);
if (response.IsSuccessStatusCode) //I get a 200 code i.e OK
{
string str = await response.Content.ReadAsStringAsync();
if (str == "SUCCESS") //str is always '{}'
{
this.Frame.Navigate(typeof(Dashboard), details);
}
}

Related

HttpClient.SendAsync() returns status code 200 even if the remote server is down

A simple login method that works just fine until I shut down my API. Then the try-catch block acts as intended, and an exception is thrown and caught but, _response comes out with a status code of "200, OK". For the love of me, I can't figure out why. Please help!
The code looks so bad mainly because of all the patching and testing I am doing on it to figure out what is happening.
HttpResponseMessage response = null;
public async Task<HttpResponseMessage> login(AuthModel model)
{
HttpResponseMessage response = null;
model.responseMessage = "";
var client = new HttpClient();
string text = "{\"email\": \""+model.email+"\",\"password\": \""+model.password+"\"}";
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(_baseURL+"/api/user/login"),
Content = new StringContent(text, Encoding.UTF8, "application/json")
};
try
{
using (response = await client.SendAsync(request))
{
HttpResponseMessage _response = null;
//response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
//_response = response;
var body = await response.Content.ReadAsStringAsync();
var token = response.Headers.GetValues("auth-token").FirstOrDefault();
model.authToken = token;
model.name = body;
model.responseMessage = "Congratulations!";
return _response;
}
else
{
model.name = "";
model.responseMessage = await response.Content.ReadAsStringAsync();
return _response;
}
}
}
catch(Exception e) {
// model.responseMessage = e.Message;
return _response;
}
}
using "HttpResponseMessage _response = new HttpResponseMessage();" was setting the _response.StatusCode to be as "200" and the code was not dealing with that.

sending headrs to web API from winForm client

i have a simple demo winform app and im trying to make a post request with header to web api.
i received access token and refreash token form the server and i stored that in text file.
and im trying to make a post request by sending the refreash token with the body and sending the access token with the header but i dont know how to include the header with the post request.
this my post method
public static async Task<string> sendMessage(string name, string contents)
{
using (HttpClient client = new HttpClient())
{
//reading the access token and refreash token from file
StreamReader sr = new StreamReader(#"C:\Users\noorm\Desktop\noor.txt");
string accessToken, refreashToken;
accessToken = sr.ReadLine();
refreashToken = sr.ReadLine();
//defining new instance of message opject
var newMessage = new messages()
{
name = name,
content = contents,
refreashToken = refreashToken
};
//sening the opject using post async and returning the response
var newPostJson = JsonConvert.SerializeObject(newMessage);
var payLoad = new StringContent(newPostJson, Encoding.UTF8, "application/json");
using (HttpResponseMessage res = await client.PostAsync(baseURL + "/messages", payLoad))
{
using (HttpContent content = res.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
return data;
}
}
}
}
return string.Empty;
}
and this is the button
private async void btnSend_Click(object sender, EventArgs e)
{
var responce = await restHelper.sendMessage(txtName.Text.Trim(),txtContent.Text.Trim());
rtxt.Text = responce;
}
You can try something like the following:
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");
this is how i was able to send the access token with the header
client.DefaultRequestHeaders.Add("x-auth-token", accessToken);

SendAsync() returning 422 Unprocessable Entity

I wrote a function using GetAsync() which works fine, but now i'd like to expand on it using SendAsync() instead [for POSTing and sofourth]; however my SendAsync() version is not working as expected, it returns a 422 unprocessible entity. (no IDE atm; sorry for minor typos)
init
var Client = new HttpClient{
BaseAddress = "https://example.com"
}
Client.DefaultRequestHeaders.UserAgent.ParseAdd("Project/1.0 (blah blah)");
...
Working GetAsync()
public async Task<string> GetResponse(string user, string pass){
var uri = $"/user/login.json?name={user}&password={pass}";
var req = await Client.GetAsync(uri);
return req.Content.Request.Content.ReasStringAsync();
}
non working SendAsync()
public async Task<string> GetResponse(string page, Dictionary<string, string> args){
//assume page = "/user/login.json" and args == {"username", "user"},{"password", "pass"}
try{
var req = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(page),
Content = new FormUrlEncodedContent(args),
}
var response = await Client.SendAsync(req);
if(response.IsSuccessStatusCode){
return await response.Content.ReasStringAsync();
return null;
}
catch{ return null }
}
note: along with the 422, the response still contains json which states "invalid Auth Token!"
What is GetAsync() doing that SendAsync() is not?
Your Send included content in the BODY of a HTTP GET request.
HTTP GET requests should not have a BODY and there are servers that wont process such requests.
Convert the dictionary to a QueryString and include it in the URI.
public async Task<string> GetResponse(string page, Dictionary<string, string> args) {
//assume page = "/user/login.json" and args == {"username", "user"},{"password", "pass"}
try {
QueryString queryString = QueryString.Create(args);
var uri = new Uri(page + queryString.ToString());
var request = new HttpRequestMessage(HttpMethod.Get, uri);
var response = await Client.SendAsync(request);
if(response.IsSuccessStatusCode){
return await response.Content.ReadAsStringAsync();
return string.Empty;
} catch { return string.Empty; }
}
Your code snippets don't show it, but are you sure the second query's URL has
$"/user/login.json?name={user}&password={pass}"
and not
$"/user/login.json"
?

Rest POST API working with POSTMAN but not working Xamarin.Forms

Heres the code to my HttpPost request
async void ContinueBtn_Clicked(object sender, EventArgs e)
{
if (!CheckValidation())
{
LoginBLL cust = new LoginBLL();
EncryptPassword encrypt = new EncryptPassword();
cust.name = txtFieldName.Text;
cust.email = txtFieldEmail.Text;
cust.Password = encrypt.HashPassword(txtFieldPass.Text);
cust.profession = txtFieldJob.Text;
cust.company = txtFieldCompany.Text;
cust.subId = 1320;
HttpClient client = new HttpClient();
string url = "https://www.example.com/api/customer/";
var uri = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response;
var json = JsonConvert.SerializeObject(cust);
var content = new StringContent(json, Encoding.UTF8, "application/json");
response = await client.PostAsync(uri, content);
if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
{
validationName.Text = await response.Content.ReadAsStringAsync();
}
else
{
validationName.Text = await response.Content.ReadAsStringAsync();
}
}
And I am getting this error when I am executing the above function
No HTTP resource was found that matches the request URI 'https://www.example.com/api/customer/'.
But it is working fine in Postman with same variables.
I even verified the JSON generated in POSTMAN with the JSON being generated in the Visual Studio it is identical.
I am running this on iphone 8 iOS 12.0

Xamarin Sending POST Data

I am attempting to send POST data to my server and get back a response. For some reason, no POST data is actually getting sent. A request is being sent to my server but the POST array is empty.
Here is my code for sending the request:
public class GlobalMethods
{
public async Task<string> callAjax(string mthd,NameValueCollection parameters)
{
var client = new HttpClient();
var content = JsonConvert.SerializeObject(parameters);
var result = await client.PostAsync("http://dev.adex-intl.com/adex/mvc/receiving/"+mthd, new StringContent(content)).ConfigureAwait(false);
var tokenJson = "";
if (result.IsSuccessStatusCode)
{
tokenJson = await result.Content.ReadAsStringAsync();
}
return tokenJson;
}
}
And here is my code that calls the above method:
public void loginPressed(object sender, EventArgs e)
{
if(String.IsNullOrEmpty(badge.Text)) {
DisplayAlert("Error", "Enter your badge number", "Ok");
} else {
IsBusy = true;
NameValueCollection parameters = new NameValueCollection();
parameters["badgetNumber"] = badge.Text;
GlobalMethods globalMethods = new GlobalMethods();
var results = globalMethods.callAjax("login", parameters);
}
}
I'm not sure what I'm doing wrong. Also, I'm a newbie to Xamarin and C# so I'm not even sure if the way I am attempting to do things is the best way.
You haven't specify the type of content that you want to send, in your case it's 'application/json', you can set it like that:
"var client = new HttpClient();
var content = new StringContent(JsonConvert.SerializeObject(parameters));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");". Also, I would suggest you to write code like that:
var uri = new Uri(url);
using (var body = new StringContent(JsonConvert.SerializeObject(data)))
{
body.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var request = new HttpRequestMessage
{
Version = new Version(1, 0),
Content = body,
Method = HttpMethod.Post,
RequestUri = uri
};
try
{
using (var response = await _client.SendAsync(request,cancellationToken))
{
if (response.IsSuccessStatusCode)
{
//Deal with success response
}
else
{
//Deal with non-success response
}
}
}
catch(Exception ex)
{
//Deal with exception.
}
}
You can use PostAsync for async sending data to server. your code should be something like this:
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "p1", "data1" },
{ "p2", "data2" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/index.php", content);
var responseString = await response.Content.ReadAsStringAsync();

Categories

Resources