Java:如何在api测试中传递rest api调用的会话id?

问题描述 投票:0回答:1

对于 UI 自动化测试,我需要执行 REST Api 调用,以获得响应。我通过 request.setheader 将会话 ID 传递到 HEADER 中,但收到的响应为:

{"result":{"success":false,"httpCode":200,"errorCode":"INVALID_SESSION_ID","errorMessage":"Session ID not provided... Kindly Login !!"}}

我尝试过显示会话 ID,似乎没问题,但我不明白的是,为什么它没有传递给 API。下面是代码:

    HttpClient httpClient = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(getUrl);

            SessionId SessionId = ((FirefoxDriver)driver).getSessionId();
             request.setHeader("Cookie", SessionId.toString());
             HttpResponse response = httpClient.execute(request);

               InputStream ips  = response.getEntity().getContent();
               BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
               if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK)
               {
                   throw new Exception(response.getStatusLine().getReasonPhrase());
               }
               StringBuilder sb = new StringBuilder();
               String s;
               while(true )
               {
                   s = buf.readLine();
                   if(s==null || s.length()==0)
                       break;
                   sb.append(s);

               }
               buf.close();
               ips.close();
               System.out.println("After parsing: "+sb.toString());

输出: 解析后:强文本

{"result":{"success":false,"httpCode":200,"errorCode":"INVALID_SESSION_ID","errorMessage":"Session ID not provided... Kindly Login !!"}}
java rest servlets selenium-webdriver web-api-testing
1个回答
1
投票

解决方案如下: 改变了,

 request.setHeader("Cookie", SessionId.toString());

 request.setHeader("sessionId", SessionId.toString());

API团队给出的API文档中提到了这一点。 然后,会话 ID 作为先前 API 调用的输出给出,需要在后续 API 调用中传递。我对此一无所知,因为我是 API 测试的新手。希望我的回答对有类似情况的人有帮助!!

© www.soinside.com 2019 - 2024. All rights reserved.