Using HttpClient in Xamarin PCL to post - c#

I'm trying to make a post to a rest api using HttpClient PCL in Xamarin. I have the following code but I'm getting a 404. Note that I don't have the real ip address here but when I use Hurl.It with the real one it connects just fine, but here just a 404. What am I missing?
string url = "http://myaddresshere/services/rest/auth/login";
string result = String.Empty;
using (var client = new HttpClient()) {
var content = new FormUrlEncodedContent(new[] {
new KeyValuePair<string, string>(txtUsername.Text, "username"),
new KeyValuePair<string, string>(txtPassword.Text, "password")
});
using (var response = await client.PostAsync(url, content)) {
using (var responseContent = response.Content) {
result = await responseContent.ReadAsStringAsync();
}
}
}

You should probably switch in your code:
new KeyValuePair<string, string>(txtUsername.Text, "username"),
new KeyValuePair<string, string>(txtPassword.Text, "password")
To:
new KeyValuePair<string, string>("username", txtUsername.Text),
new KeyValuePair<string, string>("password", txtPassword.Text)

Related

c# post request using httpparams and headers

I had a client app which was written in angular that post requests to connect/token
const body = new HttpParams()
.set('username', email)
.set('password', password)
.set('grant_type', "password")
.set('scope', "offline_access");
const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post<any>(this._baseAuthUrl + 'connect/token', body, { headers })
Now I have to write this in c#, but stuck with some part
HttpClient httpClient = new HttpClient();
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://mysite/connect/token");
requestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
How do I add HttpParams and post request properly please?
Here is the code.
var httpClient = new HttpClient();
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", email),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("scope", "offline_access")
};
var content = new FormUrlEncodedContent(pairs);
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://mysite/connect/token");
requestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
requestMessage.Content = content;
var response = await httpClient.SendAsync(requestMessage);
The above code is just an example to answer the question. But in your implementation, You should use HttpClient static and initialize it at once. Read more

I am not getting response REST API (POST) Content Type FormUrlEncode

When I try in postman it working fine and I am getting a response.
I am trying to make a request. and I am not getting any response please look into my code and let me know where I did wrong?
using (var client = new HttpClient())
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("client_id", "11223asda"),
new KeyValuePair<string, string>("client_secret", "1232asdasa"),
new KeyValuePair<string, string>("code", "authcode3"),
new KeyValuePair<string, string>("grant_type", "authorization_code"),
new KeyValuePair<string, string>("redirect_uri", "http://www.google.com/")
});
var uri = new Uri("https://sandbox-api.userdomain.com/v2/oauth2/token");
// var content = new FormUrlEncodedContent(obj);
//HttpResponseMessage response = null;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
Debug.WriteLine(response.StatusCode);
Output :
For this type of work I use this lib :
https://github.com/jgiacomini/Tiny.RestClient
var client = new TinyRestClient(new HttpClient(),"https://sandbox-api.userdomain.com/");
var response = await client.
PostRequest("v2/oauth2/token").
AddFormParameter("client_id", "France").
AddFormParameter("client_secret", "Paris").
AddFormParameter("grant_type", "Paris").
AddFormParameter("redirect_uri", "Paris").
ExecuteAsync<Response>();
Hope that helps!

Not Response get access token oauth 2.0 API UBER in ASP NET C#

I'm using this method, I recover the error "The interruption of an existing connection has been forced by the remote host"
public static async void GetAccessToken()
{
var client = new HttpClient();
// Create the HttpContent for the form to be posted.
var requestContent = new FormUrlEncodedContent(
new[] {
new KeyValuePair<string, string>("client_secret","xxxxx"),
new KeyValuePair<string, string>("client_id","xxxxx"),
new KeyValuePair<string, string>("grant_type","authorization_code"),
new KeyValuePair<string, string>("redirect_uri","http://localhost"),
new KeyValuePair<string, string>("code","xxxxx")
});
// Get the response.
HttpResponseMessage response = await client.PostAsync(
"https://domain-uber.com/oauth/v2/token",
requestContent);
// Get the response content.
HttpContent responseContent = response.Content;
// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
var result = await reader.ReadToEndAsync();
}
}

How to get object using Httpclient with response Ok in Web Api

my web api like
public async Task<IHttpActionResult> RegisterUser(User user)
{
//User Implementation here
return Ok(user);
}
I am using HTTPClient to request web api as mentioned below.
var client = new HttpClient();
string json = JsonConvert.SerializeObject(model);
var result = await client.PostAsync( "api/users", new StringContent(json, Encoding.UTF8, "application/json"));
Where i can find user object in my result request which is implemented on client application?
You can use (depands on what you need), and de-serialize it back to user object.
await result.Content.ReadAsByteArrayAsync();
//or
await result.Content.ReadAsStreamAsync();
//or
await result.Content.ReadAsStringAsync();
Fe, if your web api is returning JSON, you could use
var user = JsonConvert.DeserializeObject<User>( await result.Content.ReadAsStringAsync());
EDIT:
as cordan pointed out, you can also add reference to System.Net.Http.Formatting and use:
await result.Content.ReadAsAsync<User>()
string Baseurl = GetBaseUrl(microService);
string url = "/client-api/api/token";
using (HttpClient client = new HttpClient())`enter code here`
{
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
List<KeyValuePair<string, string>> keyValues = new List<KeyValuePair<string, string>>();
keyValues.Add(new KeyValuePair<string, string>("client_id", "5196810"));
keyValues.Add(new KeyValuePair<string, string>("grant_type", "password"));
keyValues.Add(new KeyValuePair<string, string>("username", "abc.a#gmail.com"));
keyValues.Add(new KeyValuePair<string, string>("password", "Sonata#123"));
keyValues.Add(new KeyValuePair<string, string>("platform", "FRPWeb"));
HttpContent content = new FormUrlEncodedContent(keyValues);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
content.Headers.ContentType.CharSet = "UTF-8";
var result = client.PostAsync(url, content).Result;
string resultContent = result.Content.ReadAsStringAsync().Result;
}

Google Play Music Api Unauthorized Response

First up I am aware that the api is not supported.
https://stackoverflow.com/questions/16707164/is-there-a-google-play-music-api
I have been attempting to reverse engineer some of the apis in the above post. These have been the only real source of information as no where else documents it.
I have successfully been able to implement a oauth token retrieval system.
However when I pass my token To the following I get Forbidden Error 403
Url =
https://play.google.com/music/services/streamingloadalltracks?format=jsarray
Headers =
client.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse(String.Format("GoogleLogin auth={0}", _token));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", _token);
Code
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(paramObj.Base);
client.Timeout = TimeSpan.FromSeconds(5);
if (!paramObj.skipAuth)
{
client.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse(String.Format("GoogleLogin auth={0}", _token));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", _token);
}
//client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
//client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
//client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("sdch"));
try
{
if (paramObj.post)
{
return client
.PostAsync(paramObj.method + paramObj.queryString, paramObj.content)
.Result
.Content
.ReadAsStringAsync()
//.ReadAsByteArrayAsync()
.Result;
}
else
{
return client
.GetAsync(paramObj.method + paramObj.queryString)
.Result
.Content
.ReadAsStringAsync()
//.ReadAsByteArrayAsync()
.Result;
}
}
catch (Exception exception)
{
return null;
}
}
Question is why isnt this working. I have been looking into the other apis and they implement the same calls(i think my python is pretty rusty)
Token Generator.
public string Oauth2AuthorizeUrl =>
string.Format(
"{0}?response_type=code&client_id={1}&redirect_uri={2}&scope={3}&access_type=offline",
GooglePlayAuthorizeMethod,
ClientId,
HttpUtility.UrlEncode(GooglePlayAuthorizeRedirectURL),
GooglePlayAuthorizeScope
);
public void Oauth2RetrieveToken(string code)
{
var querystring = string.Format(
"?response_type=code&code={0}client_id={1}&client_secret={3}&redirect_uri={2}&grant_type=authorization_code",
code,
ClientId,
HttpUtility.UrlEncode(GooglePlayAuthorizeRedirectURL),
ClientSecret
);
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://accounts.google.com");
client.Timeout = TimeSpan.FromSeconds(5);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("code", code),
new KeyValuePair<string, string>("client_id", ClientId),
new KeyValuePair<string, string>("client_secret", ClientSecret),
new KeyValuePair<string, string>("redirect_uri", GooglePlayAuthorizeRedirectURL),
new KeyValuePair<string, string>("grant_type", "authorization_code")
});
var result = client
.PostAsync(GooglePlayRequestToken , content)
.Result
.Content
.ReadAsStringAsync()
.Result;
var value = JObject.Parse(result);
var libs = User.Libs;
libs.GooglePlayPassword = value["access_token"].ToString();
User.UpdateSettings(libs);
}
}
Check out my attempt of an google play music API here (https://github.com/coman3/Google.Music)).
It's working perfectly when it comes to authentication and calls (although does not support 2 factor auth).

Categories