Spring RestTemplate.postForEntry, returns 403错误

Spring RestTemplate.postForEntry, returns 403 error

我想使用 RestTemplate class 与 Java 区域的服务器通信。 但是当我使用 RestTemplate 访问我的服务器时,它只显示 403(禁止)错误。

我的控制器代码:

@Controller(value="homeController")
public class HomeController {

@RequestMapping(value="/test")
public @ResponseBody Map<String, String> test(@RequestParam(value="message", required=false, defaultValue="hell world") String message){

    Map<String, String> map = new HashMap<String,String>();
    map.put("greeting", message);

    return map;
}

客户端代码:

@Test
public void test2(){
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
    map.add("message", "test");

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

    ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
    System.out.println(response.getBody());

}

如果代码运行成功,控制台应该输出"test"字。

编辑: 当我使用网络浏览器访问控制器时,它会正确显示 json 数据。

现在, 如何修复代码以使用 POST 方法与服务器通信? 谢谢

您应该指定您的 "test" 方法处理的 HTTP 方法类型。 您可以这样在 @RequestMapping 注释中执行此操作:

@RequestMapping(path="/test", method = {RequestMethod.GET, RequestMethod.POST}, 
                consumes = "application/x-www-form-urlencoded")

正如您所说,您正在使用 spring-security,您可以简单地添加一个请求拦截器并添加身份验证。 Spring 如果您不设置密码,将创建一个随机密码;它将记录在控制台中,因此您可以简单地从那里复制它。

RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(Collections.singletonList(new BasicAuthorizationInterceptor("username", "yourpassword")));

另一个(更好的)选项是自己配置身份验证。一个简单的内存验证将使

@Configuration
@EnableWebSecurity
public class RestSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().fullyAuthenticated();
        http.httpBasic();
        http.csrf().disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("username").password("yourpassword").roles("ADMIN");
    }
}