curl命令到c#代码

时间:2017-10-16 08:48:03

标签: c# curl asp.net-web-api

我有以下CURL命令

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

对应于此,我写了以下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)
        {

        }
    }

CURL命令在cmd中工作正常,但c#代码抛出错误请求(400)错误。

我哪里错了?

Thnx in Advance。

1 个答案:

答案 0 :(得分:0)

原来这是一个帖子请求和"相关性=值"应该在内容体而不是标题中传递,这里是修改后的代码:

  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)
        {

        }
    }