简体   繁体   中英

How to use HttpClient to return data from webAPI using Post?

I have this webAPI that can be called using ajax mentioned below. I am trying to achieve same result (grab data.URLs) using c# HttpClient . Its a POST request that gets me data.

Whatever I creating it encounters 404 errors. Below is the code:

$.ajax({
            type: "POST",
            crossOrigin: true,
            headers: { "Authorization-Token": "someToken" },
            url: https://someURl?Param1=" + Val1 + "&Param2=" + Val2 + "&Param3=" + Val3,
            contentType: false,
            processData: false,
            data: data,

            success: function (data) {
                document.getElementById("message").innerHTML = data.Message;

                $("#urlelement").empty(); 
                for (var i = 0; i < data.URLs.length; i++) {
                    $("#urlelement").append('<span>' + data.URLs[i] + '</span>');
                    $("#urlelement").append('<br />');
                }
            },
            error: function (data, errorThrown, status) {
                alert(data.responseText);
            }
        });
    });

My code so far: I know I'm not returning any values but just want to get to a point when there is something in the response. Dont know if the string content should be created this way neither is it applicable to this scenario

   static HttpClient client = new HttpClient();
   static string token = "some values"
   static void Main()
    {
        RunAsync().Wait();
    }

    static async Task RunAsync()
    {
       client.DefaultRequestHeaders.Accept.Clear();
       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
        client.DefaultRequestHeaders.Add("Authorization-Token", token);

        string Param1 = "val1";
        string Param2 = "val2";
        int Param3 = val3;

        var requestString = "https://someUrl?";
        var dataString = String.Format("Param1={0}Param2={1}Param3={2}", val1, val2, val3);

        var url = await getDataAsync(requestString, dataString);

    }


    static async Task<Uri> getDataAsync(string path, string data)
    {
        StringContent queryString = new StringContent(data);
        HttpResponseMessage response = await client.PostAsync(path,queryString);
        response.EnsureSuccessStatusCode();
        return response.Headers.Location;
    }

You are not addressing the parts of the URL correctly the following should work

var http = new HttpClient();
var url = String.Format("https://someUrl?Param1={0}&Param2={1}&Param3={2}", val1, val2, val3);
var response = await http.PostAsync(url, null);
var result = await response.Content.ReadAsStringAsync();

generally if you don't want to create the first part of the URL every time, you can set a base URL for the client. Take a look here and here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM