欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用RestTemplate远程调用(携带Cookie)实战案例

程序员文章站 2022-04-28 16:51:33
...

不废话,上代码

1. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
       <version>1.4.0.RELEASE</version>
    </parent>
    <groupId>com.demo</groupId>
    <artifactId>springboot_quick</artifactId>
    <version>1.0-SNAPSHOT</version>



    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <xdocreport.version>1.0.5</xdocreport.version>
    </properties>


    <dependencies>
        <!--web功能的起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- OKHttp3依赖 -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.8.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

2. 启动类

package com.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/**
 * create by: anyu
 */
@SpringBootApplication
public class MySpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class);
    }

    @Bean
    RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
        return restTemplateBuilder.build();
    }
}

3. 测试类

import com.demo.MySpringBootApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;

/**
 * @create_by: anyu
 * @craete_time 2019/7/2
 */
@SpringBootTest(classes = MySpringBootApplication.class)
@RunWith(SpringRunner.class)
public class TestDemo {

    @Test
    public void test() {
        System.out.println("hello,world");
    }

    @Autowired
    private RestTemplate restTemplate;

    /* Cookie 是根据用户名密码生成的,若不变化可直接保存数据库或者Redis,然后读取即不必反复登录 */
    /* Cookie 如果后期Cookie有失效时间了,则可用定时任务定时刷新或者失效重登重新保存即可 */
    /* 里面的请求体map 内容自定义,以及头部自定义即可适用于其他的远程请求  */

    /**
     * 模拟登录并拿到Cookie
     */
    @Test
    public void login(){
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();      //map里面是请求体的内容
        map.add("userName", "admin");
        map.add("password","123456");
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
        ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8888/xxl-job-admin/login", request, String.class);       //地址替换为自己的
        System.out.println(response.getHeaders().get("Set-Cookie").get(0));                //      XXL_JOB_LOGIN_IDENTITY=6333303830376536353837616465323835626137616465396638383162336437; Path=/; HttpOnly
    }




/*   组操作---> 对执行器进行操作  */

    /**
     * 保存组Group
     */
    @Test
    public void saveGroup(){
        HttpHeaders headers = new HttpHeaders();
        List<String> cookies =new ArrayList<String>();
        /* 登录获取Cookie 这里是直接给Cookie,可使用下方的login方法拿到Cookie给入*/
        cookies.add("XXL_JOB_LOGIN_IDENTITY=6333303830376536353837616465323835626137616465396638383162336437; Path=/; HttpOnly");       //在 header 中存入cookies
        headers.put(HttpHeaders.COOKIE,cookies);        //将cookie存入头部
        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();      //请求体给予内容
        map.add("appName", "xxl-job-executor-cdmtc-record");        //应用名称
        map.add("title", "测试执行器");      //执行器名称
        map.add("order", "1");          //排序方式
        map.add("addressType", "1");        //注册方式 :  0为
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
        ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8888/xxl-job-admin/jobgroup/save", request, String.class);
        System.out.println(response.getBody());        // {"code":200,"msg":null,"content":null}   返回此,且数据库增加数据即为成功
    }
}