gpt4 book ai didi

c# - 使用 HttpClient 将 CURL 转换为 C#

转载 作者:行者123 更新时间:2023-12-03 22:22:57 25 4
gpt4 key购买 nike

我正在尝试转换以下 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# 代码有什么想法吗?

最佳答案

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

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

关于c# - 使用 HttpClient 将 CURL 转换为 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57690755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com