2013-12-11 45 views
0

一個休息網址我有一個像調用寫在春天

@RequestMapping("/data") 
@ResponseBody 
public String property(@ModelAttribute("userDto") UserDto userDto) { 
    System.out.println(userDto.getUsername()); 
    System.out.println(userDto.getPassword()); 
    return "Hello"; 
} 

如何調用從客戶端此WebService的服務。我寫了

UserDto userDto = new UserDto(); 
    userDto.setUsername("dsf"); 
    userDto.setPassword("dsf"); 

    URL url = new URL("http://localhost:8080/home/property"); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setRequestMethod("POST"); 

     conn.setDoInput(true); 
     conn.setDoOutput(true); 

     conn.setConnectTimeout(1000); 
     conn.setReadTimeout(1000); 
     OutputStream os = conn.getOutputStream(); 

     JAXBContext jc = JAXBContext.newInstance(userDto.getClass()); 
     try { 
      jc.createMarshaller().marshal(userDto, os); 
     } 
     catch(Exception ex){ 
      ex.printStackTrace(); 
     } 



     os.flush(); 

但它不工作。我在服務端收到空值。

+0

發佈你的'web.xml'和'dispatcher-config' –

回答

1

您需要適當地對您的對象進行編碼(通常是XML或JSON)以通過流發送它。

 JAXBContext jc = JAXBContext.newInstance(obj.getClass()); 
     try (OutputStream xml = connection.getOutputStream()) { 
      jc.createMarshaller().marshal(obj, xml); 
     } 

請務必做到:

 connection.setRequestMethod("POST"); 
     connection.setDoOutput(true); 
     connection.setRequestProperty("Content-Type", "application/xml"); 

之前任何內容寫入流。

您的Web服務的方法應該是這樣的:

@RequestMapping(value = "URLHere", method = RequestMethod.POST) 
public String postGroupBody(
     @RequestBody ObjectType object, 
     otherParamsHere) { 
+0

現在它給出了一個http 415錯誤。 –

1

您可以使用RestTemplate從春天來調用這些服務。

String url = "http://localhost:8080/home/property"; 
UserDto userDto = new UserDto(); 
userDto.setUsername("dsf"); 
userDto.setPassword("dsf"); 

RestTemplate restTemplate = new RestTemplate(); 
HttpHeaders headers = new HttpHeaders(); 
headers.setContentType(MediaType.APPLICATION_JSON); 
HttpEntity<UserDto> entity = new HttpEntity<UserDto>(userDto,headers); 

ResponseEntity<ReturnedObject> result = restTemplate.exchange(url, HttpMethod.POST, entity, ReturnedObject.class); 
ReturnedObject obj = result.getBody(); 

// you will get object returned by service in result.getBody(); 

既然你沒有提到您的服務請求的格式,我假設它是JSON,而你正在使用傑克遜映射到對象轉換爲JSON,反之亦然。

1

我想你需要使用@RequestBody而不是@ModelAttribute爲你的UserDto參數。