2017-08-01 469 views
0

我想通過利用RestTemplate類與Java區域中的服務器進行通信。 但是,當我用RestTemplate訪問我的服務器時,它只顯示403(禁止)錯誤。Spring RestTemplate.postForEntry,返回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()); 

} 

如果代碼工作順利,控制檯應該輸出 「測試」 字。

編輯: 當我通過我的網絡瀏覽器訪問控制器時,它顯示正確的json數據。

現在, 如何解決通過POST方法與服務器通信的代碼? 謝謝

+0

403表示您缺少身份驗證。你在班級路上有春季保安嗎?你如何驗證你的請求? – baao

+0

真的非常感謝。問題在於彈簧安全。我沒有完成安全配置,當我刪除安全來源時,上述問題已解決!謝謝。 – PLAYMAKER

+0

我已經回答了一個簡單的基本認證快速配置類 – baao

回答

0

至於你說你使用Spring的安全性,你可以簡單地添加請求攔截並添加認證。如果你沒有設置密碼,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"); 
    } 
} 
0

您應該指定「test」方法處理的HTTP方法。 可以在@RequestMapping註釋這種方式做到這一點:

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

感謝您的答覆。我做了你的建議。但它不起作用。 – PLAYMAKER

+0

嘗試向@RequestMapping添加consumes =「application/x-www-form-urlencoded」參數 –