How To Use Spring RESTTemplate To Post Data to a Web Service
4058 ワード
springのrestelplateのpostメソッドを使用して、@RequestBodyを含む様々な変数でwebプログラムに要求を開始します.
参照: http://johnathanmarksmith.com/spring/java/javaconfig/programming/spring%20java%20configuration/spring%20mvc/web/rest/resttemplate/2013/06/18/how-to-use-spring-resttemplate-to-post-data-to-a-web-service/
@Controller
@RequestMapping("/task")
public class TaskWithTokenController extends BaseController {
@Autowired
private DataVersionService dataVersionService;
@Autowired
private TaskService taskService;
@Autowired
private SysService sysService;
@RequestMapping(value = "/{token}/{userId}/update",
method = RequestMethod.POST)
public void update(HttpServletResponse response,
@RequestBody Task task,
@PathVariable("token") String token,
@PathVariable("userId") String userId) {
LOGGER.debug("update");
try {
long taskSysId = checkTokenForTask(task.getTaskId(), token);
task.setSysId(taskSysId);
taskService.updateTaskAndAddLog(task, userId);
processSuccessForResponse(response);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
processErrorForResponse(response, e.getMessage());
}
}
private long checkTokenForTask(long taskId, String token) throws Exception {
Task t = taskService.query(taskId);
Preconditions.checkNotNull(t, " ID :[%s] ! ");
long taskSysId = t.getSysId().longValue();
List<Sys> syses = sysService.queryAllOnlineSyss();
String taskToken = null;
for (Sys sys : syses) {
if (taskSysId == sys.getSysId().longValue()) {
taskToken = sys.getToken();
break;
}
}
String err = String.format("%s token.", token);
Preconditions.checkArgument(StringUtils.isNotBlank(taskToken), err);
Preconditions.checkArgument(token.equals(taskToken), err);
return taskSysId;
}
}
@RequestMapping(value = "/updateTask", method = { RequestMethod.POST })
@ResponseBody
public AjaxResult updateTask(@RequestBody Task task,
@CookieValue(Consts.COOKIE_USER_KEY) String userId) {
LOGGER.info("user {} start update task {}", userId, task);
//
if ((task.getTaskId() == null) || (task.getTaskId() == -1)) {
return AjaxResult.errorMessage("taskId is wrong!");
}
String url = "http://localhost:8080/dmap-apiserver/api/task/{token}/{userId}/update";
try {
defaultTaskValue(task);
Map<String, String> uriVariables = Maps.newHashMap();
uriVariables.put("token", token);
uriVariables.put("userId", userId);
ResponseEntity<String> rs = restTemplate.postForEntity(url, task, String.class, uriVariables);
String body = rs.getBody();
AjaxResult ars = JSON.parseObject(body, AjaxResult.class);
return ars;
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
return AjaxResult.errorMessage(e.getMessage());
}
}
参照: http://johnathanmarksmith.com/spring/java/javaconfig/programming/spring%20java%20configuration/spring%20mvc/web/rest/resttemplate/2013/06/18/how-to-use-spring-resttemplate-to-post-data-to-a-web-service/