简体   繁体   English

C# API 初学者

[英]C# API Beginner

I have the following code as a start to create a API Call to https://jsonplaceholder.typicode.com/posts/ .我有以下代码作为开始创建 API 调用https://jsonplaceholder.typicode.com/posts/ I want to practice making the call, receive a JSON response and then..do stuff.我想练习打电话,收到 JSON 响应,然后……做点什么。

How can I finish this off to get a response so I can iterate through the response array.我怎样才能完成这个以获得响应,以便我可以遍历响应数组。

using (HttpClient client = new HttpClient())
 {

                client.BaseAddress = new Uri(URL);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,"");
                request.Content = new StringContent(URL, Encoding.UTF8,"application/json");

Wiring this in VS Code so will need to install packages if needed.在 VS Code 中接线,因此如果需要,需要安装包。

Thank you!谢谢!

You are almost there.你快到了。 Try (if you want a simple synchronous send):试试(如果你想要一个简单的同步发送):

HttpClient client = new HttpClient();
string responseString;
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri("<insert your URL>"))) {
    HttpResponseMessage response = client.SendAsync(request).Result;
    
    // Get the response content as a string
    responseString = response.Content.ReadAsStringAsync().Result;
}

Note that it's good practice to initialize one instance of HttpClient and reuse it to send multiple requests (rather than initialize one every time you need to send something).请注意,最好初始化一个 HttpClient 实例并重用它来发送多个请求(而不是每次需要发送某些内容时都初始化一个)。

Any headers, URLs and such specific to a message should be set in the HttpRequestMessage class (which should be disposed of with the "using..." term.任何特定于消息的标头、URL 等都应在 HttpRequestMessage class 中设置(应使用“使用...”术语进行处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM