我需要从现有的API调用另一个API。那可能吗?
为了执行Http
叫你应该使用位于HttpClient
命名空间中的System.Net.Http
。
欲了解更多信息:
https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.2
我已经包括了做Post
请求的示例:
POST
using System.Net.Http;
using Newtonsoft.Json;
public class MyObject
{
public string Name{get;set;}
public int ID{get;set;}
}
public async Task PerformPost(MyObject obj)
{
try
{
HttpClient client=new HttpClient();
string str = JsonConvert.SerializeObject(obj);
HttpContent content = new StringContent(str, Encoding.UTF8, "application/json");
var response = await this.client.PostAsync("http://[myhost]:[myport]/[mypath]",
content);
string resp = await response.Content.ReadAsStringAsync();
//deserialize your response using JsonConvert.DeserializeObject<T>(resp)
}
catch (Exception ex)
{
//treat your exception here ...
//Console.WriteLine("Threw in client" + ex.Message);
//throw;
}
}
public static async Task Main(){
MyObject myObject=new MyObject{ID=1,Name="name"};
await PerformPost(myObject);
}