在获得Json响应之前,我想测试一个需要身份验证的Rest API。FOr exa.如果我想访问rest API:http://192.168.xx.xx:9000/dashboards/all/list/m1/p1/sch1
然后
如果我还没有登录,这将把我重定向到login HTML页面,在登录之后,这将显示Json输出。
现在我想用java写一段放心的代码:我不知道这是否可以用它来登录。
所以我为same::写了一个简单的代码
public class TestNGSimpleTest1 {
@Test
public void testAdd() {
//expect().
//statusCode(400).
//body("Status", equalTo("Success")).
//when().
//get("http://localhost:9000/dashboards/all/list/m1/p1/sch1");
//System.out.println("Response received is ::" +res);
Response res = get("http://localhost:9000/dashboards/all/list/m1/p1/sch1");
assertEquals(200,res.getStatusCode());
String json = res.asString();
System.out.println("Response received is :: " +json);
}
所以在这里,我得到的不是Json响应,而是HTML源页面响应。
所以,我的问题是,如果可能的话,如何登录并获得Json响应。
提前谢谢。
发布于 2016-09-02 03:48:37
如果您使用来自JIRA的默认身份验证,那么抢占式身份验证就是您所需要的。下面是示例代码。
RestAssured.baseURI = System.getProperty("baseurl");
PreemptiveBasicAuthScheme authScheme = new PreemptiveBasicAuthScheme();
authScheme.setUserName("admin");
authScheme.setPassword("admin");
RestAssured.authentication = authScheme;
示例代码将帮助您在每次发送请求之前进行身份验证。
发布于 2017-10-12 07:56:27
这个方法工作得很好。除了提交登录凭据之外,它还会同时验证200状态代码
given().auth().basic(username, password).when().get("/uri/").then().statusCode(200);
发布于 2018-06-13 07:21:24
您可以尝试这样做:
given().auth().preemptive().basic(username, password).when().get("{yourApiURL}").then().statusCode(200);
https://stackoverflow.com/questions/20931722
复制相似问题