簡體   English   中英

使用HttpClient將CURL轉換為C#

[英]Convert CURL to C# using HttpClient

我正在嘗試轉換以下CURL命令:

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

C#其余客戶端方法,使用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#代碼的任何想法?

如果您設置BaseAddress請不要在PostAsync重復完整的URL

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

經過一番研究和測試之后,下面是使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;
    }

}

如果您不介意使用小型包裝庫,則可以使用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進行字符串化/解析。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM