Home > Software design >  Passing a BODY of a POST request to the server
Passing a BODY of a POST request to the server

Time:12-02

I have built a Restful-API Java(SpringBoot) and created the needed requests.

The following request is a POST Request to add new Category.

I have tested the POST request by POSTMAN, and it working as expected.

I am building the client-side in ASP.NET 5.x.x. Now the problem appear when I am calling the post request, it seems the API doesn't receive the data (@RequestBody category) that has been send from the client.

Here is a code simple of how I have created them Server Side:

@ResponseStatus(HttpStatus.CREATED)
@PostMapping(value = "/add", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public CategoryDTO create(@RequestBody CategoryDTO category) {
    log.info("Adding new Category Name: "   category.getName());
    return categoryMapper.asCategoryDTO(categoryService.save(categoryMapper.asCategory(category)));
}

Client Side

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Category category)
{
    Category newCategory = new Category();

    // Serialize the concrete class into a JSON String
    var stringPayload = JsonConvert.SerializeObject(category);
    // Wrap the JSON inside a StringContent which then can be used by the HttpClient class
    StringContent content = new StringContent(stringPayload);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

    using (var httpClient = new HttpClient())
    {
                
        using (var response = await httpClient.PostAsync("http://localhost:8080/category/add", content))
        {
                    
            string apiResponse = await response.Content.ReadAsStringAsync();
            newCategory = JsonConvert.DeserializeObject<Category>(apiResponse);
        }
    }

    return RedirectToAction("Index");
}

I don't know what is wrong there, could anybody help!

EDIT-- Here is the request via postman postman POST request

CodePudding user response:

When parsing from a JSON object, the Jackson parser needs an empty constructor, so maybe you are missing an empty constructor in your class CategoryDTO.

CodePudding user response:

I suppose that your spring boot application just blocks POST request because you didn't provide instruction how to handle requests. Try to disable csrf protection like it did here: https://stackoverflow.com/a/48935484/13314717

  • Related