HttpMediaTypeNotSupportedException

HttpMediaTypeNotSupportedException

我的 .NET 应用程序中有这个 class 用于将一些数据从客户端 (.NET) 发送到服务器 (Spring) :

    class NetworkController
    {
        private static readonly HttpClient client = new HttpClient();
        public static async Task SendUserDataAsync()
        {
            var values = new Dictionary<string, string>
            {
                { "firstName", "sunny" },
                { "lastName", "leone" },
                { "timeStamp", "test" }
            };
            var content = new FormUrlEncodedContent(values);
            var response = await client.PostAsync("http://localhost:8080/user", content);
            var responseString = await response.Content.ReadAsStringAsync();

        }
    }

Reference

在我的 Spring 引导应用程序中,我 class 调用 User :

@Entity
public class User
{
    @Id
    private String firstName;
    private String lastName;
    private String timeStamp;
    public User(){}
    @Override
    public String toString() {
        return "firstName : "+this.firstName + "\n"+"lastName : " + this.lastName;
    }
}

在我的 rest-controller 中,我有这个方法可以插入 User :

@PostMapping("/user")
    User addUser(@RequestBody User user)
    {
        System.out.println(user);//this always prints an empty line, maybe receiving nothing
        return userRepository.save(user);
    }

我收到此警告已解决[org.springframework.web.HttpMediaTypeNotSupportedException:不支持内容类型'application/x-www-form-urlencoded;charset=UTF-8']

我在 .NET 中创建了这个 class(使用 Spring 的概念),但似乎没有用:

class User
    {
        String firstName;
        String lastName;
        String timeStamp;

        public User()
        {
            firstName = "1"
            lastName = "2"
            timeStamp = "test"
        }

    }

发送对象而不是字典会不会更温和整洁?怎么做?

我该如何解决这个问题?

在您的 .NET 应用程序中,行 var content = new FormUrlEncodedContent(values); 表示请求将 HTTP header Content-Type 设置为 application/x-www-form-urlencoded

表示存储在var values = new Dictionary...中的数据将被.NET格式化为查询字符串,例如firstName=sunny&lastName=leone&timeStamp=test.

这就是您的 Sprint 服务器收到的信息。但是它想要接收 JSON 数据 ,而不是查询字符串。所以它抱怨。

为了消除错误通信,您的 .NET 应用程序应该发送 JSON 数据,例如 {"firstName": "sunny", "lastName": "leone", "timeStamp": "test"}, 正如 Spring 服务器所期望的那样。

这是一个示例代码:

HttpClient client = new HttpClient();

object anonymousObject = new
{
    firstName = "sunny",
    lastName = "leone",
    timeStamp = "test"
};

string jsonContent = JsonConvert.SerializeObject(anonymousObject);

var request = new HttpRequestMessage(HttpMethod.Post, "http://127.0.0.1:8080/user");
request.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

HttpResponseMessage response = await client.SendAsync(request);

Console.WriteLine(await response.Content.ReadAsStringAsync());

您需要安装包 Newtonsoft.Json 才能调用 JsonConvert.SerializeObject(anonymousObject),正如@alfcope 提到的 this SO answer 所指出的那样。