以下是代码demo
https://download.csdn.net/download/qq_53217825/87602397
获取get表头的api资源
[HttpPost(Name = "Post")]
//get请求
public async void Post()
{
var response = await client.GetAsync("https://jsonplaceholder.typicode.com/todos/1");//获取到接口数据
if (response.IsSuccessStatusCode)//判断是否回传正常
{
string jsonContent = await response.Content.ReadAsStringAsync();//拿到值并序列化
Todo todo = JsonConvert.DeserializeObject<Todo>(jsonContent);
Console.WriteLine("ID: {0}", todo.Id);
Console.WriteLine("Title: {0}", todo.Title);
Console.WriteLine("Completed: {0}", todo.Completed);
}
else
{
Console.WriteLine("Failed to get API data");
}
}
获取post标头的api资源
[HttpPost("PostDD")]
//post请求
public async void PostDD()
{
var todoItem = new TodoItem { Title = "Test Todo Item", Completed = false };
var content = new StringContent(JsonConvert.SerializeObject(todoItem), System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://jsonplaceholder.typicode.com/todos", content);//请求方法,路径,数据
if (response.IsSuccessStatusCode)
{
string jsonContent = await response.Content.ReadAsStringAsync();//数据
TodoItem newTodoItem = JsonConvert.DeserializeObject<TodoItem>(jsonContent);//反序列化
Console.WriteLine("ID: {0}", newTodoItem.Id);
Console.WriteLine("Title: {0}", newTodoItem.Title);
Console.WriteLine("Completed: {0}", newTodoItem.Completed);
}
else
{
Console.WriteLine("Failed to create new todo item");
}
}