Home > Mobile >  HTTP PUT request in c# with JSON content
HTTP PUT request in c# with JSON content

Time:09-02

I am trying to make an HTTP PUT request to my API that only accepts request with JSONs. I want to convert string to JSON and include this JSON in my PUT request. This is my code:

//PUT

            string word= "id: 0";
            var requestURI3 = new HttpRequestMessage();
            string url = "https://...";
            Debug.WriteLine(url);
            requestURI3.RequestUri = new Uri(url);
            requestURI3.Method = HttpMethod.Put;
            requestURI3.Headers.Add("Accept", "application/json");
            var jsonPut = JsonConvert.SerializeObject(word); //JSON 
            var contentJsonPut = new StringContent(jsonPut, Encoding.UTF8, "application/json");
            var client3 = new HttpClient();
            HttpResponseMessage responseURI3 = await client3.PutAsync(url,contentJsonPut);
            if (responseURI3.StatusCode == HttpStatusCode.OK)
            {
                Debug.WriteLine("Put made correctly");
            }
            else
            {
                Debug.WriteLine("Error in put");
                Debug.WriteLine(responseURI3.StatusCode);
            }

However, it API output is the following:

Unexpected token i in JSON at position 0 at JSON.parse (<anonymous>) at createStrictSyntaxError

CodePudding user response:

Seems to me the API expects a JSON object with id property, and you offer it a plain JSON string.

Try constructing an actual JSON object instead:

string word= "{ id: 0 }";

Or better, something like:

var payload = new { id = 0 };
var jsonPut = JsonConvert.SerializeObject(payload); //JSON 

CodePudding user response:

your code has a bug, you are trying to serialize a string for the second time, so you can do this

var jsonPut =  "{ \"id\": 0}";
var contentJsonPut = new StringContent(jsonPut, Encoding.UTF8, "application/json");

or

var id = new { id = 0 };
var jsonPut = JsonConvert.SerializeObject(id); 
var contentJsonPut = new StringContent(jsonPut, Encoding.UTF8, "application/json");
  • Related