Test controller
import com.alibaba.fastjson.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Map; @Controller public class TestController { @RequestMapping(value = "/test") @ResponseBody public JSONObject test(@RequestParam Map<String,Object> paraMap) { JSONObject obj = new JSONObject(); String strs = (String) paraMap.get("strs"); obj.put("strs",strs); obj.put("success",true); return obj; } }
get request without parameters
public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String,String> map = new HashMap<String,String>(); map.put("strs","hello"); String res = restTemplate.getForObject("http://localhost:8080/test",String.class); System.out.println(res); }
get request with parameters
public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Map<String,String> map = new HashMap<String,String>(); map.put("strs","hello"); String res = restTemplate.getForObject("http://localhost:8080/test?strs={strs}",String.class,map); System.out.println(res); }
post requests without parameters
public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); String res = restTemplate.postForObject("http://localhost:8080/test",null,String.class); System.out.println(res); }
post request with parameters
public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); map.add("strs", "hello"); String result = restTemplate.postForObject("http://localhost:8080/test", map, String.class); System.out.println(result); }