GET/POST Requst to REST API using Spring Boot

前端 未结 4 1214
北海茫月
北海茫月 2021-01-07 08:01

I have a REST Service an external server like https://api.myrestservice.com and I have a Spring Boot Application running locally on http://localhost:8080<

4条回答
  •  無奈伤痛
    2021-01-07 08:14

    This is very Simple By using Java Clients you can Use RestTemplate or UniRest That one running on Remote is simply Producer and the one which is in local is Consumer So you can exchange method of Resttemplate or get method of Unirest Example Code is here.

    @RequestMapping(value = "/testclient")
        public String testclient()
        {
            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            HttpEntity entity = new HttpEntity(headers);
            return restTemplate.exchange("https://www.mocky.io/v2/5185415ba171ea3a00704eed", HttpMethod.GET, entity, String.class).getBody();
    }
    

    For Unirest code is like this

    HttpResponse jsonResponse = null;
        try {
            jsonResponse = Unirest.get("https://www.mocky.io/v2/5185415ba171ea3a00704eed")
                    .header("accept", "application/json").queryString("apiKey", "123").asJson();
        } catch (UnirestException e) { // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonResponse.getBody().toString();
    

提交回复
热议问题