简体   繁体   中英

Passing a BODY of a POST request to the server

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.xx 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邮递员 POST 请求


EDIT

I have created another POST request but as a RequestParam instead of RequestBody

@ResponseStatus(HttpStatus.CREATED)
    @PostMapping(value = "/add", produces = MediaType.APPLICATION_JSON_VALUE)
    public CategoryDTO addCategory(@RequestParam(name = "categoryName") String categoryName){
        return categoryMapper.asCategoryDTO(categoryService.addCategory(categoryName));
    }

and created in the client side the request as following

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Category category)
{
    Category newCategory = new Category();
    var parameters = new Dictionary<string, string> { { "categoryName", category.Name } };
    var encodedContent = new FormUrlEncodedContent(parameters);

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

    return RedirectToAction("Index");
}

And It's works fine, So the problem is how to pass the data via the httpClient. which need to be of type RequestBody (the data in the body not in the header!) also as a application/json.

So how to pass the data?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM