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

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

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<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);
    }

猜你喜欢

转载自www.cnblogs.com/xiaofengfree/p/11069099.html