简体   繁体   中英

Convert CURL to C# using HttpClient

I am trying to convert the following CURL command:

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

to a C# rest client method, using HttpClient without success.

One approach i have been trying is the following:

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();
    }
}

But either i am getting some timeout exceptions or the returned result in NULL.

This is what i am getting when i run the CURL command:

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

Any ideas about how can i convert this command to working c# code?

don't repeat the full URL in PostAsync if you are setting BaseAddress

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

After some research and testing here is the code to make a corresponding to curl:

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

post request in 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;
    }

}

If you don't mind using a small wrapper library, Flurl (disclaimer: I'm the author), which wraps HttpClient and Json.NET, makes this about as simple as using cURL.

using Flurl.Http;

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

Note that JSON serializaiton is handled implicitly, so you're only ever dealing with strongly typed C# objects, rather than stringifying/parsing the JSON that goes in and comes out.

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