这是我第一次开发Java Rest API。我试图将REST API集成到Angular 7中,但出现错误。
415不支持的媒体类型
package org.jasyatra.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.jasyatra.model.AdminLogin;
import org.jasyatra.model.LoginAuthToken;
import org.jasyatra.service.AdminLoginService;
import org.jasyatra.service.LoginAuthTokenService;
@RestController
public class AdminLoginController {
@Autowired
AdminLoginService adminLoginService;
@Autowired
LoginAuthTokenService loginAuthTokenService;
@RequestMapping(value = "/admin/login", method = RequestMethod.POST, headers = "Accept=application/json")
public Map login(@RequestBody AdminLogin parameters) {
List<AdminLogin> loginResponse = adminLoginService.login(parameters);
Map<String, String> response = new HashMap<>();
if (loginResponse.size() > 0) {
response.put("result", "true");
response.put("id", Integer.toString(loginResponse.get(0).getId()));
response.put("username", loginResponse.get(0).getUsername());
response.put("role", loginResponse.get(0).getUserRole());
List<LoginAuthToken> responseToken = loginAuthTokenService.getLatestToken(loginResponse.get(0).getId(), loginResponse.get(0).getUserRole());
response.put("token", responseToken.get(0).getToken());
} else {
response.put("result", "false");
response.put("message", "Invalid username or password!");
}
return response;
}
}
adminLogin(params) {
let headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
return this.http.post(this.api_url+'/admin/login', params, options).pipe(map((response: any) => response.json()));
}
如果我未在标题中发送内容类型,则会收到此错误:
Request Method: OPTIONS
Status Code: 403 Forbidden
如果我在标头中发送内容类型,则会收到此错误:
415 Unsupported Media Type
我尝试过这种组合,但看起来它们都不对我有用。
您能指导我正确的方向吗?
谢谢
答案 0 :(得分:0)
您以'application/x-www-form-urlencoded'
的身份发送content-type
。您将需要在REST API中进行指定。您应该在consumes
中包含@RequestMapping
参数。像这样
@RequestMapping(value = "/admin/login", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, headers = "Accept=application/json")
您还需要删除方法参数上的 @RequestBody
注释
// removed @RequestBody annotation
public Map login(AdminLogin parameters) {
// .... body
}
您将需要使用RequestParam
批注并像这样修改您的方法
// using map to get all the keys & their values.
public Map login(@RequestParam Map<String, String> map){
}
// get all the form parameter in separate method parameter like so
// (key name are dummies here, use appropriate names when using)
public Map login(@RequestParam("key1") String key1, @RequestParam("key2") String key2){
}
我还认为这里不需要带有headers
参数部分的Accept
。