I am required to connect to a HTTPS
server and post data in the form of a Dictionary
to it. The server API is created by my teacher and he has provided Python code on how to post to the server, using the Python library Reguests
(see docs).
The Python template using Requests
def call_server(move): //Move is an integer value
res = requests.post(SERVER_ADRESS,
data={
"id": ID,
"move": move,
"api_key": API_KEY,
})
where of course SERVER_ADRESS
, ID
, move
and API_KEY
all are provided.
I am trying to rewrite this functionality in C#
using the HttpClient
class. I have tried using the method PostAsync
in HttpClient
(see docs) by using both a StringConent
and a FormUrlEncodedContent
object as the HttpContent
(can be seen below). However both methods results in the server responding with the error code 422 - Unprocessable Entity. Which apperently means
The server understands the content type and syntax of the request entity, but still server is unable to process the request for some reason.
My template using HttpClient
class HttpHandler
{
static readonly HttpClient client = new HttpClient();
static readonly string SERVER_ADRESS = ...
static readonly string ID = ...
static readonly string APIKey = ...
Dictionary<string, string> data;
public void callServer(int move)
{
data = new Dictionary<string, string>();
data.Add("id", ID);
data.Add("move", move.ToString());
data.Add("api_key", APIKey);
string serialized = JsonConvert.SerializeObject(data); //From Newtonsoft.Json
HttpContent stringCont = new StringContent(serialized,Encoding.UTF8,"application/json");
HttpContent byteCont = new FormUrlEncodedContent(data);
var resStringCont = client.PostAsync(SERVER_ADDRESS, stringCont);
//var resByteCont = client.PostAsync(SERVER_ADDRESS, byteCont);
}
}
Anyone more experienced with Https that can figure out why I can't successfully post to the server?