使用RestTemplate发送HTTP请求举例

使用RestTemplate发送HTTP请求(get和post)

依赖包:springboot、fastjson

代码如下:

package com.gxr.restTemplateTest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.logging.Logger;

public class RestTempTest {
    RestTemplate restTemplate = new RestTemplate();
    private final Logger logger = Logger.getLogger(this.getClass().getName());

    @Test
    public void testGet() {
        String url = "http://10.168.4.78:8085/dataPower/di/t-plugin-info/query?param=&pageNum=1&pageSize=3";
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        logger.info("返回消息:" + responseEntity.getBody());
    }

    @Test
    public void testGet2() {
        String url = "http://10.168.4.78:8085/dataPower/di/t-plugin-info/query?param=&pageNum={1}&pageSize={2}";
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, "1", "3");
        logger.info("返回消息:" + responseEntity.getBody());
    }

    @Test
    public void testPost() {
        String url = "http://10.168.4.78:8085/dataPower/metadata/t-access-sys/dataSourceByPage";
        String param = "{\"name\":\"\",\"pageNum\":1,\"pageSize\":2,\"isSource\":\"2\"}";
        JSONObject jsonObject = JSON.parseObject(param);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, jsonObject, String.class);
        logger.info("返回消息:" + responseEntity.getBody());
    }

}

 

posted @ 2020-08-18 10:23  星瑞  阅读(1756)  评论(0编辑  收藏  举报