0

I have a web site I need to use frequently but for some reason keeps lagging and am forced to interact with it on a daily basis

so I was looking around in the js code of the website and found that the website use an api on another server so for some while I was using CURL to send my requests directly to the api

but every time I need to send my request I have to reboot to my linux becaus I didn't know how to send requests from windows the command line am using is

    curl -i -s -k -X $'POST' \
    -H $'Host: WEBSERVER' -H $'Content-Length: 91' -H $'Alias: OPMzqeNCAi' -H $'Sec-Ch-Ua: ' -H $'Source: WEB' -H $'Sec-Ch-Ua-Mobile: ?0' -H $'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.91 Safari/537.36' -H $'Content-Type: application/json' -H $'Accept: application/json, text/plain, */*' -H $'Sec-Ch-Ua-Platform: \"\"' -H $'Origin: WEBSIT' -H $'Sec-Fetch-Site: cross-site' -H $'Sec-Fetch-Mode: cors' -H $'Sec-Fetch-Dest: empty' -H $'Referer: MAINWEBSITE' -H $'Accept-Encoding: gzip, deflate' -H $'Accept-Language: en-US,en;q=0.9' -H $'Connection: close' \
    -b $'SESSION=COOKI' \
    --data-binary $'{\"ALIAS\":\"EXTRA\",\"P_USERNAME\":\"WebSite\",\"P_ID\":\"INFO\",\"P_VERIFICATION_CODE\":null}' \
    $'PATH TO EXECUTE REQUEST'

I need to make this work in c# but I have no Idea where to start the request is to complicate for me to know how I should but all this parameters in c# http request and read server response if my request was processed

    curl -i -s -k -X $'POST' \
    -H $'Host: WEBSERVER' -H $'Content-Length: 91' -H $'Alias: OPMzqeNCAi' -H $'Sec-Ch-Ua: ' -H $'Source: WEB' -H $'Sec-Ch-Ua-Mobile: ?0' -H $'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.91 Safari/537.36' -H $'Content-Type: application/json' -H $'Accept: application/json, text/plain, */*' -H $'Sec-Ch-Ua-Platform: \"\"' -H $'Origin: WEBSIT' -H $'Sec-Fetch-Site: cross-site' -H $'Sec-Fetch-Mode: cors' -H $'Sec-Fetch-Dest: empty' -H $'Referer: MAINWEBSITE' -H $'Accept-Encoding: gzip, deflate' -H $'Accept-Language: en-US,en;q=0.9' -H $'Connection: close' \
    -b $'SESSION=COOKI' \
    --data-binary $'{\"ALIAS\":\"EXTRA\",\"P_USERNAME\":\"WebSite\",\"P_ID\":\"INFO\",\"P_VERIFICATION_CODE\":null}' \
    $'PATH TO EXECUTE REQUEST'

this comand line works fine on linux on windows curl couldn't make it work so I want to do so with simple c# winform app

oday ot
  • 11
  • 7
  • An http request has a URI, HTTP Headers and a Body (the contents). What have you tried? Should be simple to get working in c#, Do you want to get working in c# or Curl? – jdweng Jun 24 '23 at 15:27
  • if its possible in c# I would be great it would be a lot easier for me to deal with sever responses and , and not risk the post request to be accepted multiple times , and for what I tried nothing I don't know how to interact with web servers in c# – oday ot Jun 24 '23 at 15:31

2 Answers2

3

To send a POST request to an API in C# and read the response asynchronously, you can use the HttpClient class from the System.Net.Http namespace. Here's an example of how you can achieve that:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        // Create an HttpClient instance
        using var httpClient = new HttpClient();

        // Prepare the request data
        var requestData = "{\"ALIAS\":\"EXTRA\",\"P_USERNAME\":\"WebSite\",\"P_ID\":\"INFO\",\"P_VERIFICATION_CODE\":null}";
        var requestContent = new StringContent(requestData, System.Text.Encoding.UTF8, "application/json");

        // Add the required headers
        httpClient.DefaultRequestHeaders.Add("Host", "WEBSERVER");
        httpClient.DefaultRequestHeaders.Add("Alias", "OPMzqeNCAi");
        // Add other headers as needed...

        // Send the POST request
        var response = await httpClient.PostAsync("PATH TO EXECUTE REQUEST", requestContent);

        // Read the response
        var responseBody = await response.Content.ReadAsStringAsync();

        // Process the response data
        Console.WriteLine(responseBody);
    }
}

Make sure to replace the placeholder values such as WEBSERVER, OPMzqeNCAi, PATH TO EXECUTE REQUEST, etc., with the appropriate values from the original cURL command.

In this example, the PostAsync method sends the POST request to the specified URL asynchronously, and the ReadAsStringAsync method reads the response body as a string asynchronously.

risto
  • 483
  • 3
  • 7
  • thank you very much I will try it , and if I may ask if I lunched multiple threads doing the same request time over time until I get the needed response is that going to give me any trouble , my company rely on 3th party servers to store and process clients orders and for a month now the servers replays with errors and we have to enter data over and over until the request is processed and you can imagine how much trouble of using curl to send and many time the order get processed multiple times – oday ot Jun 25 '23 at 13:13
  • -H $'Accept: application/json, text/plain, */*' and if its no trouble would mind tell me what this header means ? – oday ot Jun 25 '23 at 13:15
  • Technically, you could make multiple requests in parallel, but I am not sure if that is a wise idea. Maybe it would be better to make requests one by one until you get a successful response and then stop making new requests. I don't know much about the website your are working with, so you can make a better decision. As for 'Accept', it is an HTTP header, you can read more detailed information [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept) – risto Jun 25 '23 at 13:21
  • httpClient.DefaultRequestHeaders.Add("Content-Length", "91"); is raising an error Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.' – oday ot Jun 25 '23 at 14:13
0

the given answer by Risto was very much helpful I had a couple of problems with some headers I need How do you set the Content-Type header for an HttpClient request? and the api was requested a cooki found the answer at How do I set a cookie on HttpClient's HttpRequestMessage and the final code is

`   using System;
    using System.Net.Http;
    using System.Threading.Tasks;
    using System.Net;

    namespace httptest
    {
        class Program
        {
            static async Task Main()
            {
                //creat a base address uri
                Uri myUri = new Uri("API ADDRESS ", UriKind.Absolute);
                // create a cookieContainer instance
                var cookieContainer = new CookieContainer();
                // Create an HttpClientHandler instance
                var handler=new HttpClientHandler({CookieContainer=cookieContainer } ;
            // Create an HttpClient instance
            var httpClient = new HttpClient(handler);
           

            // Prepare the request data
            var requestData = "post data";
            var requestContent = new StringContent(requestData, System.Text.Encoding.UTF8, "application/json");
            //requestContent.Headers.ContentLength = 91;

            // Add the required headers
            
            httpClient.DefaultRequestHeaders.Add("Host", @"WEBSITE");
            httpClient.DefaultRequestHeaders.Add("User-Agent", "AGENT");
            httpClient.DefaultRequestHeaders.Add("Accept", "application/json, text/plain, */*");
            httpClient.DefaultRequestHeaders.Add("Accept-Language","en-US,en;q=0.5");
            httpClient.DefaultRequestHeaders.Add("Accept-Encoding","gzip, deflate, br");
                // the header was giving me erros was fixed
            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
            httpClient.DefaultRequestHeaders.Add("Source","WEB");
            httpClient.DefaultRequestHeaders.Add("Alias", "value");
            httpClient.DefaultRequestHeaders.Add("Origin","WEBSITe");
            httpClient.DefaultRequestHeaders.Add("Connection","keep-alive");
            httpClient.DefaultRequestHeaders.Add("Referer","WEBSITe");
            httpClient.DefaultRequestHeaders.Add("Cookie", value);
            // fill the cookieContainer with needed cookie
            cookieContainer.Add(myUri , new Cookie(cooki namE, value));
            httpClient.DefaultRequestHeaders.Add("Sec-Fetch-Dest","empty");
            httpClient.DefaultRequestHeaders.Add("Sec-Fetch-Mode", "cors");
            httpClient.DefaultRequestHeaders.Add("Sec-Fetch-Site", "cross-site");
            // Add other headers as needed...

            // Send the POST request
            var response = await httpClient.PostAsync("TARGET PATH", requestContent);

            // Read the response
            var responseBody = await response.Content.ReadAsStringAsync();

            // Process the response data
            Console.WriteLine(responseBody);
            Console.ReadKey();
        }
    }
}`
oday ot
  • 11
  • 7