如何放心设置会话属性?在我的应用程序代码中,我们有类似的内容
String userId = request.getSession()。getAttribute(“ userid”)
如何在此设置userId作为会话属性(在可以放心的测试用例中)?
如何为所有请求(多个后续请求)保持相同的会话?
当我发送多个请求时,它考虑到每个请求都是新请求,并且会话在服务器端变得无效,因此我希望在后续调用之间保持会话。
我尝试在cookie中设置jsessionid并在第二个请求中发送它,但是当我在服务器端进行调试时,它没有加载创建的会话,而是创建了不同的会话,因此它不显示我第一次发送请求时在会话中设置的属性。
当我尝试使用直接HttpClient进行相同操作时,它可以正常工作,而使用RestAssured进行相同操作时,则无法正常工作。
正在使用HttpClient的代码是
HttpClient httpClient = util.getHttpClient();
// 1第一个请求
HttpResponse response=httpClient.execute(postRequest);
我从响应中提取了jessionid并将其设置在第二个请求中
HttpGet getRequest = new HttpGet(Client.endPointUrl);
getRequest.addHeader("content-type", "application/json");
getRequest.addHeader("accept", "application/json");
getRequest.addHeader("Origin", Client.endPointUrl);
getRequest.addHeader("Referer", Client.endPointUrl);
getRequest.addHeader("Auth-Token", authToken);
getRequest.addHeader("Set-Cookie", jsessionId);
// 2设置我从响应中提取的jessionid之后的请求
HttpResponse eventsResponse = httpClient.execute(getRequest);
以上代码运行正常,我得到了预期的响应。一种观察是我正在使用相同的httpClient对象来调用两个请求。
如果我使用RestAssured尝试相同的操作,那么它将无法正常工作。
RestAssured.baseURI = "http://localhost:8080";
Response response=RestAssured.given().header("Content-Type","application/json").
header("Origin","http://localhost:8080").
header("Referer","http://localhost:8080").
body("{"+
"\"LoginFormUserInput\":{"+
"\"username\":\"test\","+
"\"password\":\"password\""+
"}"+
"}")
.when().post("/sample/services/rest/validateLogin").then().extract().response();
JsonPath js=Util.rawToJson(response);
String sessionId=js.get("sessionID");
System.out.println(sessionId);
for (Header header:response.getHeaders()) {
if ("Set-Cookie".equals(header.getName())) {
id= header.getValue().split(";")[0].trim();
String[] arr=jsessionId.split("=");
jsessionId=arr[0];
break;
}
}
response=RestAssured.given().header("Auth-Token",sessionId).header("Content-Type","application/json").
cookie("JSESSIONID",jsessionId).
header("Origin","http://localhost:8080").
header("Referer","http://localhost:8080").
body("{}").
when().
post("/sample/services/rest/getAllBooks").then().contentType("").extract().response();
我尝试使用以下命令对所有请求重用同一个httpclient,但是没有用
RestAssured.config = RestAssured.config().httpClient( new HttpClientConfig().reuseHttpClientInstance());
答案 0 :(得分:0)