Home > Software design >  Can cmd curl and java.net.http.HttpClient be used together in Java?
Can cmd curl and java.net.http.HttpClient be used together in Java?

Time:08-19

I'm trying to understand how cmd curl and HttpClient(java.net.http.*) class can work together in 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);
    }
    
}

If I have a Controller like this in my project and just by using cmd curl itself, I can get the desired outcome I want.. like this below..

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

I'm trying not to use Postman and try to work with HttpClient Class and Cmd..And I think If I have @RestController and the cmd.. http request is just find without HttpClient.. Is there any way that I can incorporate HttpClient when trying to make a Http Request Call to my TeamController??

CodePudding user response:

Of course a java application can do http requests by executing curl. See Execute Curl from Java.

But I guess the effort of integrating curl outperforms direct handling of HTTP requests in Java. You have better performance and control over the communication altogether.

I've had quite some success using Apache httpclient.

CodePudding user response:

Apparently what you actually are looking for is this : 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);
}
  • Related