c # Consume an API using POST and header application / x-www-form-urlencoded passing a JSON

1

Can you give me a light?

I need to consume an API that requires that your header have a content-type: application/x-www-form-urlencoded . This api takes parameters in json and returns json. Using jquery I get but I need to create a console app to run via windows task scheduler, so I need to do using asp.net web api c # or something like

$.ajax({
        contentType: 'application/x-www-form-urlencoded',
        crossDomain: true,
        type: "POST",
        url: 'url',
        data: JSON.stringify(params),
        success: function (data) {
            do it
        },
        error: function (data) {
            do it
        },
        dataType: 'json',
        async: false
    });
    
asked by anonymous 08.08.2018 / 17:16

2 answers

0
using (var httpClient = new HttpClient())
        {
            var url = @"https://api-il.traffilog.com/appengine_3/5E1DCD81-5138-4A35-B271-E33D71FFFFD9/1/json";

            var jsonString = @"{
'action': {
    'name': 'user_login',
    'parameters': {
                'login_name': 'user',
        'password': '123'
    }
        }
    }";

            var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            content.Headers.Clear();
            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            HttpResponseMessage response = httpClient.PostAsync(url, content).Result;

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("ok");
            }
            else
            {
                Console.WriteLine("erro");
            }
        }

        Console.ReadKey();

    }
    
10.08.2018 / 01:21
0

Try to implement a method with the following code:

public async Task<string> PostFormUrlEncoded(string url, Dictionary<string, string> postData)
{
    using (var httpClient = new HttpClient())
    {
        using (var content = new FormUrlEncodedContent(postData))
        {
            content.Headers.Clear();
            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            return await response.Content.ReadAsStringAsync();
        }
    }
}

Calling the method using an anonymous type would look like this:

using Newtonsoft.Json;

Dictionary<string, string> dictionary = new Dictionary<string, string>();

var objetoAnonimo = new
{
    action = new
    {
        name = "user_login",
        parameters = new
        {
            login_name = "user",
            password = "123"
        }
    }
};

dictionary.Add("parametro1", System.Web.HttpUtility.UrlEncode(JsonConvert.SerializeObject(objetoAnonimo)));

string jsonReturn = await PostFormUrlEncoded<string>("http://urlapi.com", dictionary);

If you decide to create a class structure to represent that template, create these two classes below:

public class Action
{
    public string Name { get; set; }
    public Parameter Parameters { get; set; }
}

public class Parameter
{
    public string Login_Name { get; set; }
    public string Password { get; set; }
}

At the time of calling the method it would look like this:

using Newtonsoft.Json;

Dictionary<string, string> dictionary = new Dictionary<string, string>();

Action objeto = new Action();

objeto.Name = "user_login";

objeto.Parameters = new Parameter();
objeto.Parameters.Login_Name = "user";
objeto.Parameters.Password= "123";

dictionary.Add("parametro1", System.Web.HttpUtility.UrlEncode(JsonConvert.SerializeObject(objeto)));

string jsonReturn = await PostFormUrlEncoded<string>("http://urlapi.com", dictionary);
    
08.08.2018 / 19:23