gpt4 book ai didi

java - HttpMediaTypeNotSupportedException

转载 作者:行者123 更新时间:2023-11-30 05:23:00 24 4
gpt4 key购买 nike

我的.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: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not support]

我在.NET中创建了这个类(带有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 value = new Dictionary... 中的数据将被 .NET 格式化为查询字符串,例如 firstName=sunny&lastName= leone&timeStamp=测试

这就是您的 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),如this SO answer所示@alfcope 提到过。

关于java - HttpMediaTypeNotSupportedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59214285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com