【发布时间】:2019-06-19 12:55:04
【问题描述】:
我正在使用 spring 构建一个 web,它将允许用户查看存储库、他们的问题并在需要时添加新问题。当用户想要创建新问题时,就会出现问题。我收到“错误 400 错误请求”,我不明白为什么。
我尝试通过 URL 参数发送请求,但也没有成功。我也尝试使用 ObjectMapper 自动创建主体,但得到了相同的结果。所以我自己构建了身体,但是......再次得到同样的结果。
在带有注释“XXX”的那一行是软件失败的地方,并且在网络上显示了提到的错误。
@PostMapping("newIssue/{user}/{repo}/{fullName}")
public String registerUser(@PathVariable String user, @PathVariable String repo, @PathVariable String fullName, @Valid NewIssue newissue, Errors errors, Model model, OAuth2AuthenticationToken authentication) throws JsonProcessingException {
//To debug
System.out.println("### Registering issue");
//Check errors
List<String> errorsStrings = new ArrayList<>();
errors.getAllErrors().forEach(e->errorsStrings.add(e.getDefaultMessage()));
model.addAttribute("errors", errorsStrings);
model.addAttribute("newissue", newissue);
if(errors.hasErrors()) {
//To debug
System.out.println("### HAS ERRORS");
for (String err: errorsStrings )
System.out.println(" " + err);
//If has errors show again the page
return "newIssue";
}
//To debug
System.out.println("### Does not have ERRORS");
//Create the client variable
OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient( authentication.getAuthorizedClientRegistrationId(), authentication.getName() );
//Construct the necessary headers
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, "token " + client.getAccessToken().getTokenValue());
headers.add(HttpHeaders.ACCEPT, "application/vnd.github.v3+json");
//Construct the html petition's body
ObjectMapper mapper = new ObjectMapper();
//String body = mapper.writeValueAsString(newissue);
String body =
"{\n" +
" \"title\": \"" + newissue.getTitle() + "\",\n" +
" \"body\": \"" + newissue.getBody() + "\",\n" +
" \"assignees\": [],\n" +
" \"milestone\": none,\n" +
" \"labels\": []\n" +
"}"
;
//Merge the header and the body
HttpEntity<String> request = new HttpEntity<String>(body, headers);
//To debug
System.out.println("### Going to send post: ");
System.out.println(body);
//Send the issue to the api
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange("https://api.github.com/repos/" + user + "/" + repo + "/issues", HttpMethod.POST, request, String.class); //XXX
//To debug
System.out.println("### Post sent");
//To debug
System.out.println("### RESPONSE: " + response);
//Go to the repos' issues webpage
return "redirect:issues/"+user+"/"+repo+"/"+fullName;
}
我希望此方法在存储库中创建新问题,然后重定向到存储库的问题列表。 我检查了身体,对我来说似乎是正确的:
{
"title": "TestTitle",
"body": "TestBody",
"assignees": [],
"milestone": none,
"labels": []
}
这一切我都参考了 GitHub api 文档:https://developer.github.com/v3/issues/#create-an-issue
【问题讨论】:
-
根据文档,
milestone应该是一个整数。 -
如果我将“none”更改为任何整数,则响应将变为“422 Unprocessable Entity”。我想这是由于存储库中缺少任何里程碑。 (我试过 1、0 和 -1)
标签: java spring api github http-status-code-400