cmd curl和java.net.http.HttpClient可以在Java中一起使用吗?

9w11ddsr  于 2022-11-13  发布在  Java
关注(0)|答案(2)|浏览(145)

我试图理解cmd curlHttpClient(java.net.http.*)类如何在Java中一起工作。

@RestController
@RequestMapping("api/team")
@CrossOrigin(origins = "http://localhost:8081")
public class TeamController {
    @Autowired
    TeamService teamService;

    @PostMapping
    public ResponseEntity<?> addNewTeam(@RequestBody Team newTeam) {
        Team team = new Team();
        try {
            team= teamService.addNewTeam(newTeam);
        } catch(TeamAlreadyExistException e) {
            return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(team, HttpStatus.OK);
    }

    @GetMapping
    public ResponseEntity<?> getAllTeams() {
        List<Team> teams = teamService.getAllTeams();
        return new ResponseEntity<>(teams, HttpStatus.OK);
    }
    
}

如果我在我的项目中有一个这样的控制器,并且只使用cmd curl本身,我就可以得到我想要的结果..就像下面这样..

MyPath>curl -X GET "http://localhost:8081/api/team"
[{"id":1,"name":"team3"}]

我试着不使用Postman,而是尝试使用HttpClient类和Cmd..我想如果我有@RestController和cmd.. http请求只是在没有HttpClient的情况下查找..有没有什么方法可以在尝试对我的TeamController进行Http请求调用时合并HttpClient?

webghufk

webghufk1#

当然,java应用程序可以通过执行curl来完成http请求,参见Execute Curl from Java
但是我想集成curl的工作要比在Java中直接处理HTTP请求的工作更好,您可以获得更好的性能和对整个通信的控制。
我已经使用Apache httpclient取得了相当大的成功。

xkrw2x1b

xkrw2x1b2#

很显然,你真正要找的是:https://www.baeldung.com/spring-redirect-and-forward

@GetMapping("/redirectWithRedirectPrefix")
public ModelAndView redirectWithUsingRedirectPrefix(ModelMap model) {
    model.addAttribute("attribute", "redirectWithRedirectPrefix");
    return new ModelAndView("redirect:/redirectedUrl", model);
}

相关问题