简体   繁体   English

将命令卷曲到C#代码

[英]Curl Command to c# code

I have following CURL command 我有以下CURL命令

curl.exe -k  "relevance=value" --user admin:pass https://10.221.22.13:34323/api/query

corresponding to this, I have written following c# code 与此相对应,我编写了以下C#代码

    private async void RunClient(string _address, string username, string password)
    {

        HttpClient client = new HttpClient();

        string authString = username + ":" + password;

        try
        {

            var byteArray = Encoding.ASCII.GetBytes(authString);
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

            string valueString = "value";

            client.DefaultRequestHeaders.Add("relevance", valueString);

            // Send a request asynchronously and continue when complete
            HttpResponseMessage response = await client.GetAsync(_address);

            // Check that response was successful or throw exception
            response.EnsureSuccessStatusCode();


            var content = await response.Content.ReadAsStringAsync();
        }
        catch(Exception ex)
        {

        }
    }

The CURL command is working fine in cmd but the c# code throws Bad Request (400) Error. CURL命令在cmd中工作正常,但是c#代码引发Bad Request(400)错误。

Where I am wrong ? 我哪里错了?

Thnx in Advance. 提前Thnx。

Turns out it was a Post request and "relevance=value" should be passed in content body instead of header, here is the modified code : 原来这是一个Post请求,应该在内容正文而不是标题中传递“ relevance = value”,这是修改后的代码:

  private async void RunClient(string _address, string username, string password)
    {
        // Create an HttpClient instance
        HttpClient client = new HttpClient();

        string authString = username + ":" + password;

        try
        {
            //add authentication to header
            var byteArray = Encoding.ASCII.GetBytes(authString);
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

            string valueString = "value";

            var con = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("relevance", valueString)
            });

            // Send a request asynchronously and continue when complete
            HttpResponseMessage response = await client.PostAsync(_address, con);

            // Check that response was successful or throw exception
            response.EnsureSuccessStatusCode();

            var content = await response.Content.ReadAsStringAsync();
        }
        catch (Exception ex)
        {

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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