【问题标题】:Need help on RestTemplate exchange method需要有关 RestTemplate 交换方法的帮助
【发布时间】:2017-05-26 10:34:43
【问题描述】:

我需要使用 spring boot 从我的应用程序 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");
    }
}

【问题讨论】:

  • 尝试将and().httpBasic() 添加到您的configure(...) 方法中
  • 谢谢你,我会试试的
  • 仍然无法正常工作:/ ...任何建议先生请

标签: android spring-boot resttemplate


【解决方案1】:

我相信RController 类需要用@RestController 注释而不是@Controller

【讨论】:

  • 你是对的...我进行了更改但仍然无法正常工作...从我的搜索中我发现帖子需要参数来发送请求网络我想知道我该怎么做!
  • 我建议先尝试让端点在没有安全性的情况下工作,然后添加安全性
  • @RestController 只是@Controller@ResponseBody' annotations. Because @ResponseBody 的语法糖,注释已经在getMessage() 方法上方,您的建议不会影响任何事情,除了破坏@987654328 @ 方法,而不是视图名为 login 将返回字符串值 'login'。
  • @ootero oki 谢谢...如果您有教程或文档可以提供帮助
猜你喜欢
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
  • 2015-06-23
  • 2014-12-26
  • 2013-08-12
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多