HttpMediaTypeNotSupportedException

时间:2019-12-06 13:39:07

标签: java .net spring spring-boot dotnet-httpclient

我的 .NET 应用程序中有此类,用于将某些数据从客户端(.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 Boot应用程序中,我叫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中创建了此类(带有Spring的概念),但似乎没有用:

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

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

    }

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

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

在您的.NET应用程序中,行var content = new FormUrlEncodedContent(values);表示该请求将具有一个HTTP标头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所指出的那样。