【问题标题】:Convert CURL to C# using HttpClient使用 HttpClient 将 CURL 转换为 C#
【发布时间】:2019-08-28 10:52:16
【问题描述】:

我正在尝试转换以下 CURL 命令:

curl --request POST --url http://localhost:8042/tools/find --data "{\"Level\":\"Study\",\"Query\":{\"Modality\":\"MR\",\"StudyInstanceUID\":\"*\"}}"

到一个 C# 的 rest 客户端方法,使用 HttpClient 没有成功。

我一直在尝试的一种方法如下:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:8042");
    string test = "{\"Level\":\"Study\",\"Query\":{\"Modality\":\"MR\",\"StudyInstanceUID\":\"*\"}}";
    var requestContent = new StringContent(test, Encoding.UTF8, "application/x-www-form-urlencoded");

    var response = await client.PostAsync("tools/find", requestContent);

    HttpContent responseContent = response.Content;

    using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
    {
        // Write the output.
        Console.WriteLine(await reader.ReadToEndAsync());
        return await reader.ReadToEndAsync();
    }
}

但是要么我得到一些超时异常,要么返回的结果为 NULL。

这是我在运行 CURL 命令时得到的:

Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying ::1...
* TCP_NODELAY set
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8042 (#0)
> POST /tools/find HTTP/1.1
> Host: localhost:8042
> User-Agent: curl/7.55.1
> Accept: */*
> Content-Length: 66
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 66 out of 66 bytes
< HTTP/1.1 200 OK
< Connection: keep-alive
< Content-Type: application/json; charset=utf-8
< Content-Length: 1023
<
[
   "06a5bb05-acf327ff-1b1f7432-543a3572-d0778630",
   "0d2858ee-9bb9557f-6779c861-4e55604a-bbd9d561",
   "241d9063-668f6d5a-84d5e791-aae25988-cbe330e4",
   "2a47771d-a7fed498-2ea74733-6ba5b408-0af517d0",
   "2c22461c-2529103d-1c3bbf0e-5c1011b7-ef4c4702",
   "2e89270f-77b2368b-ec8f7a47-48922528-6d82a563",
   "46151c0f-a92e4ffe-b3964a0b-0a217ff0-e138a9b0",
   "4ac07d24-df6720d8-410ded38-80c42f81-029b826d",
   "6ae5803f-564d02d6-ce2d03c9-87029ebb-c5f5b783",
   "6c4dd689-5dc50cc7-7c0b07e1-231c8f06-10a50343",
   "79a0e646-d244dced-2a2ac6d0-e61e6029-38b1e61e",
   "7beb9698-c3e13f1a-5449e8c0-06f61be7-0285b222",
   "8c35bbfa-1f00d0bb-50fdddea-c8b8f085-20ef243a",
   "9a318c16-75a5cae8-3f42dd60-2ab5d0c0-664e78d1",
   "a7b43909-4ecfe2fe-12f414ad-dc1d013e-0665e60b",
   "b85380e8-e66db7da-d575e3d3-80bce548-71d5c251",
   "d07b73c3-77cad4ff-1bf045d9-d8677f33-cd4c79f5",
   "ec81b8b0-c6f95b97-2a2299ca-fa4d3f68-d79f0079",
   "ec9c971a-e66c350c-f808f182-7716b99c-4c8f6f86",
   "efe910b9-3bb0e298-c9ec181b-3985c6be-a6b74a89"
]
* Connection #0 to host localhost left intact

关于如何将此命令转换为工作 c# 代码的任何想法?

【问题讨论】:

  • Convert CURL to C#的可能重复
  • 您确定application/x-www-form-urlencoded 是您想要的内容类型吗?不应该是application/json 吗?
  • @andyb952 这个问题不是指.NET HttpClient
  • @user1859022 这是我在调用 curl 命令时得到的联系类型。也尝试使用“application/json”,但这并不能解决问题

标签: c# rest curl dotnet-httpclient


【解决方案1】:

如果您要设置BaseAddress,请不要在PostAsync 中重复完整的URL

using (var client = new HttpClient()){
    client.BaseAddress = new Uri("http://localhost:8042");
    ...        
    var response = await client.PostAsync("tools/find", requestContent);
    ...
}

【讨论】:

    【解决方案2】:

    经过一番研究和测试,这里是对应curl的代码:

    curl --request POST --url http://localhost:8042/tools/find --data "{\"Level\":\"Study\",\"Query\":{\"Modality\":\"MR\",\"StudyInstanceUID\":\"*\"}}"
    

    在 C# 中发布请求:

    public async System.Threading.Tasks.Task<string> MyMethod(string studyInstanceUID)
    {
        using (var client = new HttpClient())
        {
    
            string data = "{\"Level\":\"Study\",\"Query\":{\"Modality\":\"MR\",\"StudyInstanceUID\":\"" + studyInstanceUID + "\"}}";
    
            var requestContent = new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded");
    
            client.DefaultRequestHeaders.Add("User-Agent", "Anything");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
            if (reqAuth)
            {
                var byteArray = Encoding.ASCII.GetBytes(authString);
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
            }
    
            HttpResponseMessage response = await client.PostAsync(baseUrl + "tools/find", requestContent);
    
            var responseContent = response.Content;
    
            return responseContent.ReadAsStringAsync().Result;
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      如果您不介意使用一个小型包装库,Flurl(免责声明:我是作者),它包装了 HttpClient 和 Json.NET,让这变得像使用 cURL 一样简单。

      using Flurl.Http;
      
      var results = await "http://localhost:8042/tools/find"
          .PostJsonAsync(new { Level = "Study", Query = new { Modality = "MR", StudyInstanceUID = "*" }})
          .ReceiveJson<string[]>();
      

      请注意,JSON 序列化是隐式处理的,因此您只需要处理强类型的 C# 对象,而不是对输入和输出的 JSON 进行字符串化/解析。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-18
        • 1970-01-01
        相关资源
        最近更新 更多