Simple HTTP POST in Windows Phone 8 - c#

I have a string that I need to POST in Windows Phone 8. It looks like this:
https://www.scoreoid.com/api/getPlayers?api_key=[apiKey]&game_id=[gameID]&response=xml&username=[username]&password=[password]
This string simply returns another string (that is formatted as XML that I parse later in my code).
I have yet to find a simple solution to this like in Windows 8.
Edit: Found the solution to my problem with an assist from rciovati and the HttpClient library.
Here's my simple code:
var httpClient = new HttpClient();
return await httpClient.GetStringAsync(uri + "?" + post_data);

Using the new Http Client Library is quite easy:
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("api_key", "12345"),
new KeyValuePair<string, string>("game_id", "123456")
};
var httpClient = new HttpClient(new HttpClientHandler());
HttpResponseMessage response = await httpClient.PostAsync(url, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
You can find other informations about this library here.

Here's a pretty useful blog post from Andy Wigley about how to do Http networking on Windows Phone 8. The WinPhoneExtensions wrapper library he speaks of basically simulates the async/await model of network programming you can do in Win8.
http://blogs.msdn.com/b/andy_wigley/archive/2013/02/07/async-and-await-for-http-networking-on-windows-phone.aspx

Related

Xamarin.Forms - HttpClient GetAsync or PostAsync sometimes takes too long

I am using Xamarin.Forms and I am using HttpClient GetAsync and PostAsync to make calls to an api, my problem is the client is complaining that the application is too slow when it makes an api call. Is there anyways I can speed up this process or is there another faster way to call an api? Here is an example method:
public async Task<List<SubCatClass>> GetSubCategories(int category)
{
var client = new HttpClient();
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("category", category.ToString())
});
var response = await client.PostAsync(string.Format("https://exmample.com/api/index.php?action=getSubCategories"), content);
var responseString = await response.Content.ReadAsStringAsync();
List<SubCatClass> items = JsonConvert.DeserializeObject<List<SubCatClass>>(responseString);
return items;
}
And here is how I am calling it.
await webService.GetSubCategories(item.categoryid);
The api I have full control over the code (PHP) and the server.
Any help would be much appreciated.
Thanks in advance.
UPDATE
I called the api in postman and here was the results
You can try using ModernHttpClient, it will increase your speed than using default by Xamarin

Correct way of adding HttpClient PUT parameters? - Porting TypeScript REST call to C#

I'm partially porting a TypeScript application to C#. The application needs to perform a certain REST call on a webservice. The webservice is written in C# and the specific method has the following signature:
public async Task<IHttpActionResult> RegisterDevice(DeviceRegistration deviceRegistration)
The original application (TypeScript) makes the REST call in the following manner:
this.$http.put(this.Configuration.registrationEndpointUrl, {
field1: value1,
field2: value2,
field3: value3
})
I searched StackOverflow on how to do the call and found a post explaining how to do it. I then created the following in the C# version:
var pairs = new List<KeyValuePair<string, string>>() {
new KeyValuePair<string, string>("field1", Settings.Value1),
new KeyValuePair<string, string>("field2", Settings.Value2),
new KeyValuePair<string, string>("field3", "value3")
};
var content = new FormUrlEncodedContent(pairs);
var response = await Client.PutAsync(Configuration.RegistrationUrl, content);
However this just returns an empty response. I'm thinking something is wrong with the FormUrlEncodedContent? What is the correct way of doing this call in C#?
EDIT: Client initialisation code:
private static async Task<HttpClient> CreateClient() {
await Authenticator.VerifyAuthentication();
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("x-zumo-auth", Settings.OAuthToken);
client.DefaultRequestHeaders.Add("x-oauth-provider", Settings.OAuthProvider.Value.ToString());
return client;
}
Instead of using the method
var response = await Client.PutAsync(Configuration.RegistrationUrl, content);
You can use this
var response = await Client.PutAsJsonAsync(Configuration.RegistrationUrl, content);

FormUrlEncodedContent works but StringContent does not

I have a question about those 2 httpcontents.
I've made an webapi (php), copy from this: http://www.9lessons.info/2012/05/create-restful-services-api-in-php.html
I re-used the Rest.inc.php, and implement my own api file.
I try to call this api from .Net (I'm a .Net developer) - a simple WinForm Application - the FormUrlEncodedContent works but the StringContent does not.
This my code:
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("username", username);
parameters.Add("title", title);
parameters.Add("text", text);
var jsonString = JsonConvert.SerializeObject(parameters);
var content = new StringContent(jsonString, Encoding.UTF8, "text/json");
//var content = new FormUrlEncodedContent(parameters);
PostData(url, content);
And the reason why I want to use StringContent: in the real data, sometime the parameters will contain a byte[] (photo), and the FormUrlEncodedContent can't handle it
Please help me
Thanks alot!
They are very different formats. If the api does not have a smart model binder like Asp.Net Web API then it will not work. You can always base64 encode your byte array which is the typical way to transmit bytes via HTTP.

PostAsync is not working when URL contain port

My .net application try to access external API by using the code below...
using (var keyClient = new HttpClient())
{
keyClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["webshopurl"]);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("api_username",
ConfigurationManager.AppSettings["webshopAPIUserName"]),
new KeyValuePair<string, string>("api_password",
ConfigurationManager.AppSettings["webshopAPIPassword"])
});
var result = keyClient.PostAsync("/api/v1/key.php", content).Result;
token = result.Content.ReadAsStringAsync().Result;
}
When calling from local machine it works properly. But when it is hosted in online server URL such like http://app.test.net:5000/test it is not calling to the API. If we host such a URL like http://app.test.net/test it is working properly.
What is the reason for this?
Why are you using .Result to unpack the result? It's a lot better to use await to get the result from an async method.
.Result can cause a deadlock if you are not being careful with the context.
Stephen Cleary has a really nice articles that goes into more details.
Don't Block on Async Code

Want to pass header field through rest api in windows phone application

I am having a issue in solving REST api call in windows phone application.
The situation is something :
I want to Pass two parameter named here "session_token" and "userid" as header in rest api call i am using the following code but the expected output is not matched with the postman out put (attached in screen shot)
I have the following code
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Connection);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-ype", "application/x-www-form-urlencoded");
client.DefaultRequestHeaders.TryAddWithoutValidation("session_token", "sdfsffsdfsdffsfsdfsdfsdfsdf");
client.DefaultRequestHeaders.TryAddWithoutValidation("userid", "sdfsdfsdfsdfsdfsdd");
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("changepasswordinput", "{\"oldpassword\":\"sdfsdfdf\",\"newpassword\":\"sdfsdfsdf\"}"));
HttpContent content = new FormUrlEncodedContent(postData);
HttpResponseMessage response = await client.PostAsync("changepassword", content);
if (response.IsSuccessStatusCode)
{
var outputstring = await response.Content.ReadAsStringAsync();
responseBaseClass = await response.Content.ReadAsAsync<ResponseBaseClass>();
}
}
Please tell me where i am doing wrong.
Thanks in advance.
You are doing it right, the headers are there. Just click on the Headers(2) tab in Postman on the first screenshot and you will see them.

Categories

Resources