【发布时间】:2020-02-15 03:08:53
【问题描述】:
我正在运行一个接受 http 请求的 Spring Boot 服务器。 我已经用 curl 对其进行了广泛的测试,并且效果很好。 但是,当我尝试在 java 客户端中发送请求并接收响应时,我得到:
java.io.IOException:服务器返回 HTTP 响应代码:URL 为 400:
在服务器端我得到:
[org.springframework.web.bind.MissingServletRequestParameterException:必需的字符串参数'用户名'不存在]
这是我尝试使用的spring boot方法:
@PostMapping(path="/CreateAccount") // Map ONLY POST Requests
public @ResponseBody String CreateUser (@RequestParam String Username
, @RequestParam String Password) {
// @ResponseBody means the returned String is the response, not a view name
// @RequestParam means it is a parameter from the GET or POST request
//make sure the username and password is valid input
if (!validateInput(Username) || !validateInput(Password))
{
return "Username and Password cannot be blank";
}
//make sure the username is unique
//check if Username is equal to any other User's username
User u = findByUsername(Username);
//if a user was found in the table
if ( !(u == null) )
{
return "Username already taken\nPlease choose another";
}
//if we are here we are clear to make a new user
User n = new User();
n.setUsername(Username);
n.setPassword(Password);
n.setRole("Player");
userRepository.save(n);
//THIS CAUSES AN ERROR
//create a stat object to be added to the table
Stats s = new Stats();
s.setUsername(Username);
statRepository.save(s);
//create a token for the user
String usrToken = createToken(tokenSize);
//add the username and token to hashmap
userTokens.put(Username, usrToken);
//return this user's token
return usrToken;
}
这是我的客户:
public static void CreateAccount(String username, String password)
{
try
{
String s = serverURL + "/CreateAccount";
URL url = new URL(s);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; utf-8");
connection.setDoOutput(true);
String json = "[{\n\"Username\"=\"Jake\",\"Password\"=\"123\"\n}]";
System.out.println(json);
OutputStream os = connection.getOutputStream();
DataOutputStream out = new DataOutputStream( os );
byte[] input = json.getBytes("utf-8");
out.writeUTF(json);
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = br.readLine();
System.out.println(response);
}
catch (Exception e)
{
System.out.println("#");
System.out.println(e);
}
}
我认为这与我的 json 格式有关,但我反复尝试,无论我如何格式化,我都会遇到同样的错误。
【问题讨论】:
-
POST 参数不作为 JSON 传递,它们在由
&分隔的正文中作为name=value对传递。
标签: java json spring-boot http