Example usage for org.springframework.web.client RestTemplate getForObject

List of usage examples for org.springframework.web.client RestTemplate getForObject

Introduction

In this page you can find the example usage for org.springframework.web.client RestTemplate getForObject.

Prototype

@Override
    @Nullable
    public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException 

Source Link

Usage

From source file:ArenaService.TestRest.java

public static void main(String[] args) {
    RestTemplate restTemplate = new RestTemplate();
    Arenas response = restTemplate.getForObject(
            "https://api.worldoftanks.eu/wot/encyclopedia/arenas/?application_id=102bb26eb57f82e3b28572f345fef266",
            Arenas.class);
    for (Arena a : response.getData().values()) {
        System.out.println("Map: " + a.getName_i18n());
    }/*  w ww  .  ja v a  2 s.  c o m*/
    // System.out.println(response.getData());
    //String response = restTemplate.getForObject("https://api.worldoftanks.eu/wot/encyclopedia/arenas/?application_id=102bb26eb57f82e3b28572f345fef266", String.class);
    //System.out.println("Response: " + response);
}

From source file:com.github.hexsmith.spring.boot.rest.client.ApacheHttpClient.java

public static void main(String[] args) {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    HttpClient httpClient = httpClientBuilder.build();

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

    RestTemplate restTemplate = new RestTemplate(factory);

    User user = restTemplate.getForObject("http://localhost:8080/json/user", User.class);

    System.out.println(user);/*from  w ww .  j  a v a  2 s.  com*/

}

From source file:com.tianjunwei.RestTemplateTest.java

public static void main(String[] args) {

    RestTemplate restTemplate = new RestTemplate();
    try {/*from  ww  w.j av a  2s .  com*/
        System.err.println(restTemplate.getForObject("http://localhost:8090/product/get.action", String.class));
    } catch (RestClientResponseException e) {
        System.err.println(e.getResponseBodyAsString());
    }

}

From source file:ui.TestRest.java

public static void main(String[] args) throws IOException {
    RestTemplate restTemplate = new RestTemplate();
    String response = restTemplate.getForObject(
            "http://api.apixu.com/v1/current.json?key=aebe5a3f024040ff9bf112640160705&q=Brussel", String.class);
    //System.out.println(response.getConditions().toString());
    System.out.println(response.toString());

    //System.out.println(response.toString());

    //RestTemplate restTemplate = new RestTemplate();
    // ObjectMapper jacksonObjectMapper = new ObjectMapper();

    // LinkedHashMap map= restTemplate.getForObject("http://api.apixu.com/v1/current.json?key=aebe5a3f024040ff9bf112640160705&q=Brussel", LinkedHashMap.class);
    //Weather weatherDescription = jacksonObjectMapper.convertValue(map.get("current"), Weather.class);

    //String weatherCondition = jacksonObjectMapper.convertValue(map.get("current"), String.class);

    //  Current current = restTemplate.getForObject("http://api.apixu.com/v1/current.json?key=aebe5a3f024040ff9bf112640160705&q=Brussel", Current.class);
    // DatabaseFacade service = new DatabaseFacade();

    // System.out.println(service.getWeather());
    // System.out.println(weatherCondition.toString());
    // System.out.println(service.getWeather());

}

From source file:com.stackoverflow.so32806530.App.java

/**
 * Program EP./* www  .  j a  v a2s.c  o m*/
 * @param args CLI args
 *
 * @throws URISyntaxException
 * @throws IOException
 */
public static void main(final String[] args) throws URISyntaxException, IOException {
    // ---------- Read response.xml -----
    final String xml = new String(
            Files.readAllBytes(Paths.get(App.class.getClassLoader().getResource("response.xml").toURI())),
            Charset.forName("UTF-8"));

    // ---------- starts fake API server -----
    final WireMockServer wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig().port(8089));
    wireMockServer.stubFor(get(urlMatching("/v2/discovery/events.*")).willReturn(
            aResponse().withHeader("Content-type", "application/xml").withStatus(200).withBody(xml)));
    wireMockServer.start();
    // ---------------------------------------

    try {
        final String name = "foo";
        final String APIKEY = "MYAPI";
        final String URL = "http://localhost:8089/v2/discovery/events?apikey=" + APIKEY;
        final String readyUrl = URL + "&what=" + name;
        final RestTemplate restTemplate = new RestTemplate();
        final EventsResponse eventResponse = restTemplate.getForObject(readyUrl, EventsResponse.class);

        log.info("Seatwave: {}", eventResponse.getEvents().size());

        for (final Event event : eventResponse.getEvents()) {
            log.info("EventID: {}", event.getId());
        }
    } catch (final Exception ex) {
        log.error("Something went wrong", ex);
    }

    // ---------- stops fake API server ------
    wireMockServer.stop();
    // ---------------------------------------
}

From source file:uk.ac.ebi.ep.adapter.ebeye.EbeyeRestSearch.java

public static void main(String args[]) {
    RestTemplate restTemplate = new RestTemplate();
    String url = "http://www.ebi.ac.uk/ebisearch/ws/rest/uniprot?query=cancer&format=json&size=20";

    EbeyeRestSearch result1 = restTemplate.getForObject(url, EbeyeRestSearch.class);
    List<EbeyeSearchResult> list = result1.getResults();
    System.out.println("List " + list.size());

    //        ResponseEntity<EbeyeSearchResult> result = restTemplate.exchange(url, 
    //  HttpMethod.GET, null, EbeyeSearchResult.class);

    //EbeyeSearchResult result = restTemplate.getForObject(url, EbeyeSearchResult.class);

    System.out.println("Obj " + list);

    for (EbeyeSearchResult result : list) {
        //        System.out.println("Acc:    " + result.getAcc());
        //        System.out.println("Id:   " + result.getId());
        //        System.out.println("Source:   " + result.getSource());
    }/*from   www . j a  va 2 s  .c o  m*/
    //System.out.println("Entries: " + result1);
}

From source file:com.garyclayburg.scimclient.ScimApp.java

public static void main(String[] args) {
    /*//from   w  ww . j  av a2 s .co m
    String plainCreds = "willie:p@ssword";
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);
            
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);
    */

    HttpClient httpClient = new DefaultHttpClient();
    final AuthHttpComponentsClientHttpRequestFactory requestFactory = new AuthHttpComponentsClientHttpRequestFactory(
            httpClient, new HttpHost("localhost"), "bjensen", "password");
    //            new AuthHttpComponentsClientHttpRequestFactory(httpClient,host,userName,password);
    final RestTemplate restTemplate = new RestTemplate(requestFactory);

    //        RestTemplate restTemplate = new RestTemplate();
    SCIMusersDoc page = restTemplate.getForObject("http://localhost:8080/Users", SCIMusersDoc.class);
    log.info("total results: " + page.getTotalResults());
    List<String> schemas = page.getSchemas();
    for (String schema : schemas) {
        log.info("schema found: " + schema);
    }
    for (Resources user : page.getResources()) {
        log.info("username " + user.getUserName());
        log.info("formatted name:" + user.getName().getFormatted());
        log.info("work phone: " + (user.getPhoneNumbers().get(0).getValue()));
    }

    //        User userMatch =
}

From source file:kymr.github.io.future.LoadTest.java

public static void main(String[] args) throws InterruptedException {
    ExecutorService es = Executors.newFixedThreadPool(100);

    RestTemplate rt = new RestTemplate();
    String url = "http://localhost:8080/dr";

    StopWatch main = new StopWatch();
    main.start();//from w  w  w .j av  a2 s.c  o  m

    for (int i = 0; i < 100; i++) {
        es.execute(() -> {
            int idx = counter.addAndGet(1);
            log.info("Thread {}", idx);

            StopWatch sw = new StopWatch();
            sw.start();

            rt.getForObject(url, String.class);

            sw.stop();
            log.info("Elapsed: {} -> {}", idx, sw.getTotalTimeSeconds());
        });
    }

    es.shutdown();
    es.awaitTermination(100, TimeUnit.SECONDS);

    main.stop();
    log.info("Total: {}", main.getTotalTimeSeconds());
}

From source file:com.mycompany.asyncreq.Main.java

public static void main(String[] args) throws JsonProcessingException, JSONException, IOException {

    Configuration config = new Configuration();
    // Name tables with lowercase_underscore_separated
    RestTemplate restTemplate = new RestTemplate();
    config.setNamingStrategy(new ImprovedNamingStrategy());
    try {//from  ww  w.  j a  v a 2s  .c  om

        ArrayList<String> ArrReq = GenData();
        String addr;
        for (Iterator<String> i = ArrReq.iterator(); i.hasNext();) {
            try {
                addr = i.next();
                Thread.sleep(1000);
                Root tRoot = restTemplate.getForObject(addr, Root.class);
                tRoot.addr = addr;
                if (!tRoot.dataset.isEmpty())
                    if (tRoot.dataset.size() == tRoot.validation.count.value)
                        ObjToCsv(tRoot, "all");

                    else {
                        for (int reg = 1; reg < 5; reg++) {
                            Thread.sleep(1000);
                            addr = "http://comtrade.un.org/api/get?max=50000&type=C&freq=M&px=HS&ps=2014&r=804&p="
                                    + tRoot.dataset.get(0).getptCode() + "&rg=" + reg + "&cc=All&fmt=json";
                            Root tRootImp = restTemplate.getForObject(addr, Root.class);
                            tRootImp.addr = addr;
                            if (!tRootImp.dataset.isEmpty())
                                if (tRootImp.dataset.size() == tRootImp.validation.count.value)
                                    ObjToCsv(tRootImp, Integer.toString(reg));
                                else
                                    System.out.println("addr:  " + tRootImp.addr + "\n");
                        }
                    }
                else
                    System.out.println("addr:  " + tRoot.addr + ":null" + "\n");
            } catch (Exception e) {
                System.err.println(e.getMessage());

            }
        }

    } catch (Exception e) {
        System.err.println("Got an exception! ");
        System.err.println(e.getMessage());
    }
}

From source file:client.ChalkJavaClient.java

/**
 * @param args the command line arguments
 *///  w  w w  . ja v a2 s. c  om
public static void main(String[] args) {
    RestTemplate restTemplate = new RestTemplate();
    User henky = new User("Henkyyy123", "0612345678");
    henky = restTemplate.postForObject("http://localhost:8080/user/register", henky, User.class);
    System.out.println("Registered user: " + henky.getUserName() + " " + henky.getPhoneNumber());
    User sjef = new User("GekkeSjef", "0687654321");
    sjef = restTemplate.postForObject("http://localhost:8080/user/register", sjef, User.class);
    System.out.println("Registered user: " + sjef.getUserName() + " " + sjef.getPhoneNumber());
    Message message = new Message(henky, sjef, "Hallo, alles goed?");
    message = restTemplate.postForObject("http://localhost:8080/message/create", message, Message.class);
    System.out.println("Sent message: " + message.getId() + " " + message.getText() + " to "
            + message.getReceiver().getUserName() + " from " + message.getSender().getUserName() + " sent at "
            + message.getTimeSent().toString());
    Message[] messages = restTemplate.getForObject("http://localhost:8080/message/find?receiver="
            + sjef.getPhoneNumber() + "&sender=" + henky.getPhoneNumber(), Message[].class);
    for (Message m : messages) {
        System.out.println(
                "Got message: " + m.getId() + " " + m.getText() + " to " + m.getReceiver().getUserName()
                        + " from " + m.getSender().getUserName() + " sent at " + m.getTimeSent().toString());
    }
}