hosting tips

Pass Data Using WebAPI In C# Windows Forms

Here, I have described the simplest way to create a Web API POST method in a Windows application using C#. First, we have to create a Web API POST method where we pass the data as a string. In this method, we will use the HttpWebRequest object to get or post the data from the URL.

Use the below namespaces.

using System;
using System.IO;
using System.Net;
using System.Text;

Now, let us create the POST method.

public class WebPostMethod
{
    public string Post(string postData, string URL)
    {
        string responseFromServer = "";
        WebRequest request = WebRequest.Create(URL);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = postData.Length;
        using (var stream = request.GetRequestStream())
        {
            stream.Write(postData.ToUtf8Bytes(), 0, postData.Length);
        }

        WebResponse response = request.GetResponse();
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            responseFromServer = reader.ReadToEnd();
        }

        return responseFromServer;
    }
}

Here, we will create aWeb API GET method in Windows application using C#.

public class WebGetMethod
{
    public string Get(string URL)
    {
        string jsonString = "";
        WebRequest request = WebRequest.Create(URL);
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";
        using (var response = request.GetResponse())
        {
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                jsonString = reader.ReadToEnd();
            }
        }

        return jsonString;
    }
}

Now, let’s create the method to invoke the webPostMethod and webGetMethod.

public class CallWebServices
{
    public void Call()
    {
        string postData = "user_id=25689&passwd=123456";
        string URL = "http://xxx-xx-xxx-xx-xxx.xxxxxxx-x.amazonaws.com/index.php/somefunctionname";
        var data = WebPostMethod.Post(postData, URL);
        Console.WriteLine(data);

        var getData = WebGetMethod.Get(URL);
        Console.WriteLine(getData);
    }
}

Here, we get the result as a JSON string.

I hope this is useful for all readers. Happy Coding!

ASP.NET Core 8 Hosting Recommendation

HostForLIFE.eu

HostForLIFE.eu is a popular recommendation that offers various hosting choices. Starting from shared hosting to dedicated servers, you will find options fit for beginners and popular websites. It offers various hosting choices if you want to scale up. Also, you get flexible billing plans where you can choose to purchase a subscription even for one or six months.