Spring Boot TestRestTemplate:传递会话ID

时间:2017-11-03 03:32:14

标签: java spring session spring-boot cookies

我有一些带有一些测试的Spring Boot应用程序。应用程序的'happy-path'要求用户发送启动会话的请求,然后它可以向其他服务发出其他请求。

我正在尝试测试这些其他服务,但我需要先启动一个会话。我的心态如下:

  1. 点击会话开始端点
  2. 从该请求中获取会话Cookie
  3. 将该Cookie用于测试期间的未来请求。
  4. 为了达到这个目的,我得到了这个烂摊子:

        String s = t.postForEntity(loginUrl, remoteSessionPacket, String.class)
                .getHeaders()
                .get("Set-Cookie").get(0);
        String[] split = s.split(";");
        String sessionId = "";
        for (String s1 : split) {
            if(s1.contains("SESSION"))
            {
                sessionId = s1;
            }
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("SESSION", sessionId);
        HttpEntity<?> httpEntity = new HttpEntity<>(headers);
    
        RemoteDTOPacket= new RemoteDTOPacket();
        packet.Token = UUID.randomUUID().toString();
        String url = "http://localhost:" + port + "/domain/SomeFunction";
        ResponseEntity<ResponsePacket> response = t.postForEntity(url, packet, ResponsePacket.class, httpEntity);
        Assert.assertEquals(0, (long) response.getBody().count);
    

    显然,这不起作用,抛弃了错误。

    有谁知道如何完成我想要做的事情?

    非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

会话ID存储在cookie中,存储在&#34; Cookie&#34;标头 - 不在单独的请求标头中。这样的事情应该有效:

private void setYoutubePlayer() {

    YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();

    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    transaction.add(R.id.youtube_layout, youTubePlayerFragment)
            .addToBackStack(youTubePlayerFragment.getClass().getName()).commitAllowingStateLoss();

    youTubePlayerFragment.initialize(Config.DEVELOPER_KEY, new OnInitializedListener() {

        @Override
        public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
            if (!wasRestored) {
                player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);

                player.loadVideo(Config.YOUTUBE_VIDEO_CODE);
                player.play();

            }

        }

        @Override
        public void onInitializationFailure(Provider provider, YouTubeInitializationResult error) {
            // YouTube error
            String errorMessage = error.toString();
            Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
            Log.d("errorMessage:", errorMessage);
        }
    });
}

或者你可以得到确切的会话ID cookie,它最有可能存储在&#34; JSESSIONID&#34;键。