因此,您在C#中构建此文件,试图发布到本地运行的API中,GET正常工作,但是当我尝试发布时,它告诉我:
Content type 'application/x-www-form-urlencoded;charset=utf-8' not supported
,即使我使用了client.DefaultRequestHeaders.Accept.new MediaTypeWithQualityHeaderValue("application/json"));
并且我认为这将有助于我将其定义为json。但是,对于C#和JSON来说,这是一种新事物,因此可能会有很多东西我可以编写得更短或更短。
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Flurl.Http;
namespace HoloChessAPIListener
{
public class Move
{
public long moveNr { get; set; }
public long gameId { get; set; }
public bool playerWhite { get; set; }
public string chessNotation { get; set; }
}
class Program
{
static HttpClient client = new HttpClient();
static string path = "http://localhost:8080";
static void ShowMove(Move move)
{
Console.WriteLine($"MoveNr: {move.moveNr}\tGameId: " +
$"{move.gameId}\tPlayerWhite: {move.playerWhite}\tChessNotation: {move.chessNotation}");
}
static async Task<string> CreateMoveAsync(Move move)
{
var json = JsonConvert.SerializeObject(move, Formatting.Indented);
var pathString = path + "/games/1/moves";
var responseString = await pathString
.PostUrlEncodedAsync(json)
.ReceiveString();
return responseString;
}
static async Task<Move[]> GetMoveAsync(string path1)
{
//Get Json
var json = await client.GetStringAsync(path1);
//Handle Json
Move[] move = JsonConvert.DeserializeObject<Move[]>(json);
return move;
}
static void Main()
{
RunAsync().GetAwaiter().GetResult();
}
static async Task RunAsync()
{
client.BaseAddress = new Uri("http://localhost:8080");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
try
{
Move move1 = new Move()
{
moveNr = 1,
gameId = 1,
playerWhite = true,
chessNotation = "CH1"
};
var url = await CreateMoveAsync(move1);
Console.WriteLine($"Created at {url}");
Move[] move;
// Get the move
move = await GetMoveAsync(url);
ShowMove(move[0]);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
}
如果我在浏览器中调用API,这就是API给我的:
[{"moveNr":1,"gameId":4,"playerWhite":true,"chessNotation":"Nc6"},{"moveNr":2,"gameId":4,"playerWhite":false,"chessNotation":"Nc7"},{"moveNr":3,"gameId":4,"playerWhite":true,"chessNotation":"Nc8"}]