简体   繁体   English

将 POST 请求的 BODY 传递给服务器

[英]Passing a BODY of a POST request to the server

I have built a Restful-API Java(SpringBoot) and created the needed requests.我已经构建了一个 Restful-API Java(SpringBoot) 并创建了所需的请求。

The following request is a POST Request to add new Category.以下请求是添加新类别的 POST 请求。

I have tested the POST request by POSTMAN, and it working as expected.我已经测试了 POSTMAN 的 POST 请求,它按预期工作。

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.我正在 ASP.NET 5.xx 中构建客户端现在当我调用发布请求时出现问题,似乎 API 没有收到从客户端发送的数据(@RequestBody 类别)。

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 请求


EDIT 编辑

I have created another POST request but as a RequestParam instead of RequestBody我创建了另一个 POST 请求,但作为 RequestParam 而不是 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.它工作正常,所以问题是如何通过 httpClient 传递数据。 which need to be of type RequestBody (the data in the body not in the header!) also as a application/json.它需要是 RequestBody 类型(正文中的数据而不是标题中的数据!)也作为应用程序/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. 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.我想您的 spring 启动应用程序只是阻止 POST 请求,因为您没有提供如何处理请求的说明。 Try to disable csrf protection like it did here: https://stackoverflow.com/a/48935484/13314717尝试像这里一样禁用 csrf 保护: https://stackoverflow.com/a/48935484/13314717

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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