Call and use the Web API in winform using C # .net

I am new and create winform application. In which I have to use the API for a simple CRUD operation. My client shared an API with me and asked me to send the data in JSON form.

API: http://blabla.com/blabla/api/login-valida

KEY: "HelloWorld"

Value: {"email": " user@gmail.com ", "password": "123456", "time": "2015-09-22 10:15:20"}

Answer: Login_id

How can I convert the data to JSON, call the API using the POST method and get a response?

EDIT Somewhere on stackoverflow I found this solution

public static void POST(string url, string jsonContent)
    {
        url="blabla.com/api/blala" + url;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseURL);
        request.Method = "POST";

        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        Byte[] byteArray = encoding.GetBytes(jsonContent);

        request.ContentLength = byteArray.Length;
        request.ContentType = @"application/json";

        using (Stream dataStream = request.GetRequestStream())
        {
            dataStream.Write(byteArray, 0, byteArray.Length);
        }
        long length = 0;
        try
        {
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                length = response.ContentLength;

            }
        }
        catch
        {
            throw;
        }
    }
//on my login button click 
    private void btnLogin_Click(object sender, EventArgs e)
    {
        CallAPI.POST("login-validate", "{ \"email\":" + txtUserName.Text + " ,\"password\":" + txtPassword.Text + ",\"time\": " + DateTime.Now.ToString("yyyy-MM-dd h:mm tt") + "}");
    }

I got an exception that says: "The remote server returned an error: (404) Not Found."

+7
3

, , Web API:
, . :

Install-Package Microsoft.AspNet.WebApi.Client

// HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
    // Get the URI of the created resource.
    Uri gizmoUrl = response.Headers.Location;
}
+10
+4

.

https://www.nuget.org/packages/RestSharp

GitHub: https://github.com/restsharp/RestSharp

::

    public Customer GetCustomerDetailsByCustomerId(int id)
    {
        var client = new RestClient("http://localhost:3000/Api/GetCustomerDetailsByCustomerId/" + id);
        var request = new RestRequest(Method.GET);
        request.AddHeader("X-Token-Key", "dsds-sdsdsds-swrwerfd-dfdfd");
        IRestResponse response = client.Execute(request);
        var content = response.Content; // raw content as string
        dynamic json = JsonConvert.DeserializeObject(content);
        JObject customerObjJson = jsonData.CustomerObj;
        var customerObj = customerObjJson.ToObject<Customer>();
        return customerObj;
    }
+3
source

Source: https://habr.com/ru/post/1532065/


All Articles