RestTemplate常用的get和post带参数请求

测试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 paraMap) {
        JSONObject obj = new JSONObject();
        String strs = (String) paraMap.get("strs");
        obj.put("strs",strs);
        obj.put("success",true);
        return obj;
    }
}

get请求不带参数

public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        Map map = new HashMap();
        map.put("strs","hello");
        String res = restTemplate.getForObject("http://localhost:8080/test",String.class);
        System.out.println(res);
    }

 

get请求带参数

public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        Map map = new HashMap();
        map.put("strs","hello");
        String res = restTemplate.getForObject("http://localhost:8080/test?strs={strs}",String.class,map);
        System.out.println(res);
    }

post请求不带参数

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请求带参数

public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap map = new LinkedMultiValueMap();
        map.add("strs", "hello");
        String result = restTemplate.postForObject("http://localhost:8080/test", map, String.class);
        System.out.println(result);
    }

 

转载于:https://www.cnblogs.com/xiaofengfree/p/11069099.html

你可能感兴趣的:(RestTemplate常用的get和post带参数请求)