需要有关RestTemplate交换方法的帮助

时间:2017-05-26 10:34:43

标签: android spring-boot resttemplate

我需要通过使用spring boot从我的app android进行身份验证我尝试发送这样的用户名和密码:

HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setAuthorization(authHeader);
        requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

使用restTemplate.exchange发出网络请求:

ResponseEntity<Message> response = restTemplate.exchange(url, HttpMethod.POST,new HttpEntity<Object>(requestHeaders), Message.class);

但我仍然得到空响应。

这是我的代码服务器:

控制器:

@Controller  
public class RController {  

    @RequestMapping(value={"/welcome"})
    public @ResponseBody Message getMessage() { 
    return new Message(100, "Congratulations!", "You have accessed a Basic 
        Auth protected resource.");
    }

    @RequestMapping(value={"/login"})
        public String login() {
        return "login";
    }  
}

配置

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("select username,password, enabled from users where username=?")
                .authoritiesByUsernameQuery("select username, role from user_roles where username=?");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN")
            .anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout()
            .permitAll();
        http.exceptionHandling().accessDeniedPage("/403");
    }
}

1 个答案:

答案 0 :(得分:0)

我认为RController课程需要使用@RestController而不是@Controller进行注释