DemoController.java
package com.springboot.test.restful;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController // ・・・ 1
@RequestMapping("/api/v1/cities") // ・・・ 2
public class DemoController {
@RequestMapping(method = RequestMethod.GET) // ・・・ 3
public List<String> getCities() {
List<String> rtn = new ArrayList<String>();
rtn.add("GET1");
rtn.add("GET2");
return rtn;
}
@RequestMapping(value = "{id}", method = RequestMethod.GET) // ・・・ 4
public String getCity(@PathVariable Integer id) {
return "id";
}
@RequestMapping(method=RequestMethod.POST) // g
public Customer postCustomer(@RequestBody Customer customer) {
customer.setEmail("hahaha");
List<String> strList = new ArrayList<String>();
strList.add("qqq");
strList.add("www");
customer.setStrList(strList);
return customer;
}
@RequestMapping(value = "{id}/foods", method = RequestMethod.GET) // ・・・ 5
public List<String> getFoods(@PathVariable Integer id) {
List<String> rtn = new ArrayList<String>();
rtn.add("foods1");
rtn.add("foods2");
return rtn;
}
@RequestMapping(value = "{id}/restaurants", method = RequestMethod.GET) // ・・・ 6
public List<String> getRestaurants(@PathVariable Integer id) {
List<String> rtn = new ArrayList<String>();
rtn.add("restaurants1");
rtn.add("restaurants2");
return rtn;
}
}
RestClientController.java
package com.springboot.test.restful.client;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.springboot.test.restful.Kehu;
@RestController // ・・・ 1
@RequestMapping("/client") // ・・・ 2
public class RestClientController {
@RequestMapping(method = RequestMethod.GET) // ・・・ 3
public void getCities() {
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/api/v1/cities";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
Kehu c = new Kehu();
c.setId(1);
c.setName("name1");
c.setEmail("email1");
HttpEntity entity = new HttpEntity(c, headers);
ResponseEntity a = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
System.out.println("OK");
}
}
Customer.java
package com.springboot.test.restful;
import java.util.List;
public class Customer {
private Integer id;
private String name;
private String email;
private List<String> strList;
}