REST Assured api

原创
2016/09/05 17:24
阅读数 294

Class RestAssured

·         java.lang.Object

·          

·         io.restassured.RestAssured

·        

 

public class RestAssured

extends Object

 

REST Assured是一个简单的基于REST services的框架,它支持POST, GET, PUT, DELETE, HEAD, PATCH and OPTIONS请求及验证请求结果。样例:

假定Get请求为:           (to http://localhost:8080/lotto)

返回Json格式数据:

1.   {

2.   "lotto":{

3.     "lottoId":5,

4.     "winning-numbers":[2,45,34,23,7,5,3],

5.     "winners":[{

6.       "winnerId":23,

7.       "numbers":[2,45,34,23,3,5]

8.     },{

9.       "winnerId":54,

10.     "numbers":[52,3,12,11,18,22]

11.   }]

12.  }

13. }

 

 

REST assured 能够很简单的帮助你发送GET请求并校验相应结果。假如你想校验lottoId等于5,你可以这样做:

 

 get("/lotto").then().assertThat().body("lotto.lottoId", equalTo(5));

 

或者假定你要检查winnerId 是23和54:

 get("/lotto").then().assertThat().body("lotto.winners.winnerId", hasItems(23, 54));

 

14.XML can be verified in a similar way. Imagine that a POST request to

        (检查XML返回的标签内容,例如请求为)

http://localhost:8080/greetXML

返回:

15. <greeting>

16.     <firstName>{params("firstName")}</firstName>

17.     <lastName>{params("lastName")}</lastName>

18.   </greeting>

 

i.e. it sends back a greeting based on the firstName and lastName parameter sent in the request. You can easily perform and verify e.g. the firstName with REST assured:

对于发送的请求,返回值带有参数firstName 和 lastName,能够使用REST assured 验证firstName

with().parameters("firstName", "John", "lastName", "Doe").when().post("/greetXML").then().assertThat().body("greeting.firstName", equalTo("John"));

 如果你想校验firstName 和lastName 可以这样:

 

 with().parameters("firstName", "John", "lastName", "Doe").when().post("/greetXML").then().assertThat().body("greeting.firstName", equalTo("John")).and().body("greeting.lastName", equalTo("Doe"));

 

或者稍微简短些:

 with().parameters("firstName", "John", "lastName", "Doe").when().post("/greetXML").then().assertThat().body("greeting.firstName", equalTo("John"), "greeting.lastName", equalTo("Doe"));

 

19.同样可以使用X-path检查XML响应内容,例如:

 given().parameters("firstName", "John", "lastName", "Doe").when().post("/greetXML").then().assertThat().body(hasXPath("/greeting/firstName", containsString("Jo")));

 

或者

 with().parameters("firstName", "John", "lastName", "Doe").post("/greetXML").then().body(hasXPath("/greeting/firstName[text()='John']"));

 

20.XML response bodies can also be verified against an XML.

同样可以校验XML响应本体中的Schema (XSD) 或者 DTD


XSD 样例:

get("/carRecords").then().assertThat().body(matchesXsd(xsd));

 

DTD 样例:

 get("/videos").then().assertThat().body(matchesDtd(dtd));

 

matchesXsd and matchesDtd are Hamcrest matchers which you can import from RestAssuredMatchers.

matchesXsd 和 matchesDtd的样式可以从RestAssuredMatchers导入

 

21.Besides specifying request parameters you can also specify headers, cookies, body and content type.

而且请求参数同样支持headers, cookies, body 和content type

·         Cookie:

·          given().cookie("username", "John").when().get("/cookie").then().assertThat().body(equalTo("username"));

 

·         Headers:

·          given().header("MyHeader", "Something").and(). ..

·          given().headers("MyHeader", "Something", "MyOtherHeader", "SomethingElse").and(). ..

 

·         Content Type:

·          given().contentType(ContentType.TEXT). ..

 

·         Body:

·          given().request().body("some body"). .. // 使用在POST和PUT请求

·          given().request().body(new byte[]{42}). .. //使用在POST和PUT请求

 

22.  同样可以用来检查status code, status line, cookies, headers, content type 和 body.

·         Cookie:

·          expect().cookie("cookieName", "cookieValue"). ..

·          expect().cookies("cookieName1", "cookieValue1", "cookieName2", "cookieValue2"). ..

·          expect().cookies("cookieName1", "cookieValue1", "cookieName2", containsString("Value2")). ..

 

·         Status:

·          get("/x").then().assertThat().statusCode(200). ..

·          get("/x").then().assertThat().statusLine("something"). ..

·          get("/x").then().assertThat().statusLine(containsString("some")). ..

 

·         Headers:

·          get("/x").then().assertThat().header("headerName", "headerValue"). ..

·          get("/x").then().assertThat().headers("headerName1", "headerValue1", "headerName2", "headerValue2"). ..

·          get("/x").then().assertThat().headers("headerName1", "headerValue1", "headerName2", containsString("Value2")). ..

 

·         Content-Type:

·          get("/x").then().assertThat().contentType(ContentType.JSON). ..

 

·         REST Assured 同样支持Jackson, Gson 和 JAXB 的mapping请求和响应

 

·         样例:

·          Greeting greeting = get("/greeting").as(Greeting.class);

 

 Greeting greeting = new Greeting();

 greeting.setFirstName("John");

 greeting.setLastName("Doe");

 

 given().body(greeting).when().post("/greeting");

 

See the javadoc for the body method for more details.

·         Full body/content matching:

·          get("/x").then().assertThat().body(equalsTo("something")). ..

·          get("/x").then().assertThat().content(equalsTo("something")). .. // Same as above

 

23.REST assured 同样支持身份认证,例如基础验证(用户名、密码):

 given().auth().basic("username", "password").when().get("/secured/hello").then().statusCode(200);

 

其他也支持第三方验证.

24.REST assured默认请求的是本地8080端口,如果需要请求不同的端口可以:

given().port(80). ..

 

或者:

 .. when().get("http://myhost.org:80/doSomething");

 

25.url带参数:

26. ..when().get("/name?firstName=John&lastName=Doe");

 

27.你能够使用 XmlPath 或者 JsonPath 来解析响应中的 XML数据或者 JSON数据。

1.  XML 样例:

2.              String xml = post("/greetXML?firstName=John&lastName=Doe").andReturn().asString();

3.              // Now use XmlPath to get the first and last name

4.              String firstName = with(xml).get("greeting.firstName");

5.              String lastName = with(xml).get("greeting.firstName");

6.   

7.              // or a bit more efficiently:

8.              XmlPath xmlPath = new XmlPath(xml).setRoot("greeting");

9.              String firstName = xmlPath.get("firstName");

10.            String lastName = xmlPath.get("lastName");

       

11.JSON 样例:

12.            String json = get("/lotto").asString();

13.            // Now use JsonPath to get data out of the JSON body

14.            int lottoId = with(json).getInt("lotto.lottoId);

15.            List winnerIds = with(json).get("lotto.winners.winnerId");

16. 

17.            // or a bit more efficiently:

18.            JsonPath jsonPath = new JsonPath(json).setRoot("lotto");

19.            int lottoId = jsonPath.getInt("lottoId");

20.            List winnderIds = jsonPath.get("winnders.winnderId");

       

28.REST Assured providers predefined parsers for e.g. HTML, XML and JSON. But you can parse other kinds of content by registering a predefined parser for unsupported content-types by using:

29. RestAssured.registerParser(<content-type>, <parser>);

 

E.g. to register that content-type 'application/custom' should be parsed using the XML parser do:

 RestAssured.registerParser("application/custom", Parser.XML);

 

You can also unregister a parser using:

 RestAssured.unregisterParser("application/custom");

 

If can also specify a default parser for all content-types that do not match a pre-defined or registered parser. This is also useful if the response doesn't contain a content-type at all:

 RestAssured.defaultParser = Parser.JSON;

 

30.If you need to re-use a specification in multiple tests or multiple requests you can use the ResponseSpecBuilder and RequestSpecBuilder like this:

31. RequestSpecification requestSpec = new RequestSpecBuilder().addParameter("parameter1", "value1").build();

32. ResponseSpecification responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build();

33. 

34. given().

35.         spec(requestSpec).

36. when().

37.        get("/something");

38. then().

39.         spec(responseSpec).

40.         body("x.y.z", equalTo("something"));

 

41.You can also create filters and add to the request specification. A filter allows you to inspect and alter a request before it's actually committed and also inspect and alter the response before it's returned to the expectations. You can regard it as an "around advice" in AOP terms. Filters can be used to implement custom authentication schemes, session management, logging etc. E.g.

42. given().filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(302)). ..

 

will log/print the response body to after each request.

43.You can also change the default base URI, base path, port, authentication scheme, root path and filters for all subsequent requests:

44. RestAssured.baseURI = "http://myhost.org";

45. RestAssured.port = 80;

46. RestAssured.basePath = "/resource";

47. RestAssured.authentication = basic("username", "password");

48. RestAssured.rootPath = "store.book";

 

This means that a request like e.g. get("/hello") goes to: http://myhost.org:8080/resource/hello which basic authentication credentials "username" and "password". See rootPath for more info about setting the root paths, filters(java.util.List) for setting default filters
You can reset to the standard baseURI (localhost), basePath (empty), standard port (8080), default authentication scheme (none), default parser (none) and default root path (empty string) using:

 RestAssured.reset();

 

In order to use REST assured effectively it's recommended to statically import methods from the following classes:

·         io.restassured.RestAssured.*

·         io.restassured.matcher.RestAssuredMatchers.*

·         org.hamcrest.Matchers.*

·          

·         Field Summary

Fields 

Modifier and Type

Field and Description

static AuthenticationScheme

authentication

Set an authentication scheme that should be used for each request.

static String

basePath

A base path that's added to the baseURI by REST assured when making requests.

static String

baseURI

The base URI that's used by REST assured when making requests if a non-fully qualified URI is used in the request.

static RestAssuredConfig

config

Define a configuration for e.g.

static AuthenticationScheme

DEFAULT_AUTH 

static String

DEFAULT_BODY_ROOT_PATH 

static String

DEFAULT_PATH 

static int

DEFAULT_PORT 

static String

DEFAULT_SESSION_ID_VALUE 

static String

DEFAULT_URI 

static boolean

DEFAULT_URL_ENCODING_ENABLED 

static Parser

defaultParser

Specify a default parser.

static int

port

The port that's used by REST assured when it's left out of the specified URI when making a request.

static ProxySpecification

proxy

Specify a default proxy that REST Assured will use for all requests (unless overridden by individual tests).

static RequestSpecification

requestSpecification

Specify a default request specification that will be sent with each request.

static ResponseSpecification

responseSpecification

Specify a default response specification that will be sent with each request.

static String

rootPath

Set the default root path of the response body so that you don't need to write the entire path for each expectation.

static String

sessionId

Set the default session id value that'll be used for each request.

static int

UNDEFINED_PORT 

static boolean

urlEncodingEnabled

Specifies if Rest Assured should url encode the URL automatically.

·         Constructor Summary

Constructors 

Constructor and Description

RestAssured() 

·         Method Summary

All Methods Static Methods Concrete Methods Deprecated Methods 

Modifier and Type

Method and Description

static AuthenticationScheme

basic(String userName, String password)

Create a http basic authentication scheme.

static AuthenticationScheme

certificate(String certURL, String password)

Sets a certificate to be used for SSL authentication.

static AuthenticationScheme

certificate(String certURL, String password, CertificateAuthSettings certificateAuthSettings)

Sets a certificate to be used for SSL authentication.

static AuthenticationScheme

certificate(String trustStorePath, String trustStorePassword, String keyStorePath, String keyStorePassword, CertificateAuthSettings certificateAuthSettings)

Sets a certificate to be used for SSL authentication.

static RestAssuredConfig

config() 

static Response

delete()

Perform a DELETE request to the statically configured path (by default http://localhost:8080).

static Response

delete(String path, Map<String,?> pathParams)

Perform a DELETE request to a path.

static Response

delete(String path, Object... pathParams)

Perform a DELETE request to a path.

static Response

delete(URI uri)

Perform a DELETE request to a uri.

static Response

delete(URL url)

Perform a DELETE request to a url.

static AuthenticationScheme

digest(String userName, String password)

Use http digest authentication.

static void

enableLoggingOfRequestAndResponseIfValidationFails()

Enable logging of both the request and the response if REST Assureds test validation fails with log detail equal to LogDetail.ALL.

static void

enableLoggingOfRequestAndResponseIfValidationFails(LogDetail logDetail)

Enable logging of both the request and the response if REST Assureds test validation fails with the specified log detail.

static ResponseSpecification

expect()

Start building the response part of the test io.restassured.specification.

static List<Filter>

filters() 

static void

filters(Filter filter, Filter... additionalFilters)

Add default filters to apply to each request.

static void

filters(List<Filter> filters)

Add default filters that will be applied to each request.

static AuthenticationScheme

form(String userName, String password)

Use form authentication.

static AuthenticationScheme

form(String userName, String password, FormAuthConfig config)

Use form authentication with the supplied configuration.

static Response

get()

Perform a GET request to the statically configured path (by default http://localhost:8080).

static Response

get(String path, Map<String,?> pathParams)

Perform a GET request to a path.

static Response

get(String path, Object... pathParams)

Perform a GET request to a path.

static Response

get(URI uri)

Perform a GET request to a uri.

static Response

get(URL url)

Perform a GET request to a url.

static RequestSpecification

given()

Start building the request part of the test io.restassured.specification.

static RequestSpecification

given(RequestSpecification requestSpecification)

When you're only interested in supplying a predefined request specification without a response specification then you can use this method.

static RequestSender

given(RequestSpecification requestSpecification, ResponseSpecification responseSpecification)

When you have long specifications it can be better to split up the definition of response and request specifications in multiple lines.

static Response

head()

Perform a HEAD request to the statically configured path (by default http://localhost:8080).

static Response

head(String path, Map<String,?> pathParams)

Perform a HEAD request to a path.

static Response

head(String path, Object... pathParams)

Perform a HEAD request to a path.

static Response

head(URI uri)

Perform a HEAD request to a uri.

static Response

head(URL url)

Perform a HEAD request to a url.

static void

keyStore(File pathToJks, String password)

Use a keystore located on the file-system.

static void

keyStore(String password)

Uses the user default keystore stored in @{user.home}/.keystore *

static void

keyStore(String pathToJks, String password)

Apply a keystore for all requests

static AuthenticationScheme

oauth(String consumerKey, String consumerSecret, String accessToken, String secretToken)

Excerpt from the HttpBuilder docs:
OAuth sign the request.

static AuthenticationScheme

oauth(String consumerKey, String consumerSecret, String accessToken, String secretToken, OAuthSignature signature)

Excerpt from the HttpBuilder docs:
OAuth sign the request.

static AuthenticationScheme

oauth2(String accessToken)

OAuth sign the request.

static AuthenticationScheme

oauth2(String accessToken, OAuthSignature signature)

OAuth sign the request.

static void

objectMapper(ObjectMapper objectMapper)

Set a object mapper that'll be used when serializing and deserializing Java objects to and from it's document representation (XML, JSON etc).

static Response

options()

Perform a OPTIONS request to the statically configured path (by default http://localhost:8080).

static Response

options(String path, Map<String,?> pathParams)

Perform a OPTIONS request to a path.

static Response

options(String path, Object... pathParams)

Perform a OPTIONS request to a path.

static Response

options(URI uri)

Perform a OPTIONS request to a uri.

static Response

options(URL url)

Perform a OPTIONS request to a url.

static Response

patch()

Perform a PATCH request to the statically configured path (by default http://localhost:8080).

static Response

patch(String path, Map<String,?> pathParams)

Perform a PATCH request to a path.

static Response

patch(String path, Object... pathParams)

Perform a PATCH request to a path.

static Response

patch(URI uri)

Perform a PATCH request to a uri.

static Response

patch(URL url)

Perform a PATCH request to a url.

static Response

post()

Perform a POST request to the statically configured path (by default http://localhost:8080).

static Response

post(String path, Map<String,?> pathParams)

Perform a POST request to a path.

static Response

post(String path, Object... pathParams)

Perform a POST request to a path.

static Response

post(URI uri)

Perform a POST request to a uri.

static Response

post(URL url)

Perform a POST request to a url.

static PreemptiveAuthProvider

preemptive()

Return the http preemptive authentication specification for setting up preemptive authentication requests.

static void

proxy(int port)

Instruct REST Assured to connect to a proxy on the specified port on localhost.

static void

proxy(ProxySpecification proxySpecification)

Instruct REST Assured to connect to a proxy using a ProxySpecification.

static void

proxy(String host)

Instruct REST Assured to connect to a proxy on the specified host on port 8888.

static void

proxy(String host, int port)

Instruct REST Assured to connect to a proxy on the specified host and port.

static void

proxy(String host, int port, String scheme)

Instruct REST Assured to connect to a proxy on the specified port on localhost with a specific scheme.

static void

proxy(URI uri)

Instruct REST Assured to connect to a proxy using a URI.

static Response

put()

Perform a PUT request to the statically configured path (by default http://localhost:8080).

static Response

put(String path, Object... pathParams)

Perform a PUT request to a path.

static Response

put(URI uri)

Perform a PUT request to a uri.

static Response

put(URL url)

Perform a PUT request to a url.

static void

registerParser(String contentType, Parser parser)

Register a custom content-type to be parsed using a predefined parser.

static void

replaceFiltersWith(Filter filter, Filter... additionalFilters)

Sets the default filters to apply to each request.

static void

replaceFiltersWith(List<Filter> filters)

Sets the default filters to apply to each request.

static Response

request(Method method)

Perform a request to the pre-configured path (by default http://localhost:8080).

static Response

request(Method method, String path, Object... pathParams)

Perform a HTTP request to a path.

static Response

request(Method method, URI uri)

Perform a request to a uri.

static Response

request(Method method, URL url)

Perform a request to a url.

static Response

request(String method)

Perform a custom HTTP request to the pre-configured path (by default http://localhost:8080).

static Response

request(String method, String path, Object... pathParams)

Perform a custom HTTP request to a path.

static Response

request(String method, URI uri)

Perform a custom HTTP request to a uri.

static Response

request(String method, URL url)

Perform a custom HTTP request to a url.

static void

reset()

Resets the baseURI, basePath, port, authentication and rootPath, filters(java.util.List), requestSpecification, responseSpecification, urlEncodingEnabled, config, sessionId and proxy to their default values of "http://localhost", "", -1, no authentication, <empty string>, null, null, <empty list>, null, null, none, true, new RestAssuredConfig(), null and null.

static void

trustStore(File pathToJks, String password)

Use a trust store located on the file-system.

static void

trustStore(KeyStore truststore)

Specify a trust store that'll be used for HTTPS requests.

static void

trustStore(String pathToJks, String password)

The following documentation is taken from https://github.com/jgritman/httpbuilder/wiki/SSL:

static void

unregisterParser(String contentType)

Unregister the parser associated with the provided content-type

static void

useRelaxedHTTPSValidation()

Use relaxed HTTP validation with protocol .

static void

useRelaxedHTTPSValidation(String protocol)

Use relaxed HTTP validation with a specific protocol.

static RequestSender

when()

Start building the DSL expression by sending a request without any parameters or headers etc.

static RequestSpecification

with()

Start building the request part of the test io.restassured.specification.

static List<Argument>

withArgs(Object firstArgument, Object... additionalArguments)

Create a list of arguments that can be used to create parts of the path in a body/content expression.

static List<Argument>

withArguments(Object firstArgument, Object... additionalArguments)

Deprecated. 

Use withArgs(Object, Object...) instead

static List<Argument>

withNoArgs()

Create a list of no arguments that can be used to create parts of the path in a response specification for JSON, XML or HTML validation.

static List<Argument>

withNoArguments()

Deprecated. 

Use withNoArgs() instead

·         Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

·          

·         Field Detail

·         DEFAULT_URI

public static final String DEFAULT_URI

See Also:

Constant Field Values

·         DEFAULT_BODY_ROOT_PATH

public static final String DEFAULT_BODY_ROOT_PATH

See Also:

Constant Field Values

·         DEFAULT_PORT

public static final int DEFAULT_PORT

See Also:

Constant Field Values

·         UNDEFINED_PORT

public static final int UNDEFINED_PORT

See Also:

Constant Field Values

·         DEFAULT_PATH

public static final String DEFAULT_PATH

See Also:

Constant Field Values

·         DEFAULT_AUTH

public static final AuthenticationScheme DEFAULT_AUTH

·         DEFAULT_URL_ENCODING_ENABLED

public static final boolean DEFAULT_URL_ENCODING_ENABLED

See Also:

Constant Field Values

·         DEFAULT_SESSION_ID_VALUE

public static final String DEFAULT_SESSION_ID_VALUE

·         baseURI

public static String baseURI

The base URI that's used by REST assured when making requests if a non-fully qualified URI is used in the request. Default value is "http://localhost".

·         port

public static int port

The port that's used by REST assured when it's left out of the specified URI when making a request. Default port will evaluate to 8080.

·         basePath

public static String basePath

A base path that's added to the baseURI by REST assured when making requests. E.g. let's say that the baseURI is http://localhost and basePath is /resource then

 ..when().get("/something");

 

will make a request to http://localhost/resource. Default basePath value is empty.

·         urlEncodingEnabled

public static boolean urlEncodingEnabled

Specifies if Rest Assured should url encode the URL automatically. Usually this is a recommended but in some cases e.g. the query parameters are already be encoded before you provide them to Rest Assured then it's useful to disable URL encoding. For example:

 RestAssured.baseURI = "https://jira.atlassian.com";

 RestAssured.port = 443;

 RestAssured.urlEncodingEnabled = false; // Because "query" is already url encoded

 String query = "project%20=%20BAM%20AND%20issuetype%20=%20Bug";

 String response = get("/rest/api/2.0.alpha1/search?jql={q}",query).andReturn().asString();

 ...

 

The query is already url encoded so you need to disable Rest Assureds url encoding to prevent double encoding.

·         authentication

public static AuthenticationScheme authentication

Set an authentication scheme that should be used for each request. By default no authentication is used. If you have specified an authentication scheme and wish to override it for a single request then you can do this using:

     given().auth().none()..

 

·         config

public static RestAssuredConfig config

Define a configuration for e.g. redirection settings and http client parameters (default is new RestAssuredConfig()). E.g.

 RestAssured.config = config().redirect(redirectConfig().followRedirects(true).and().maxRedirects(0));

 

config() can be statically imported from RestAssuredConfig.

·         rootPath

public static String rootPath

Set the default root path of the response body so that you don't need to write the entire path for each expectation. E.g. instead of writing:

 get(..).then().assertThat().

          body("x.y.firstName", is(..)).

          body("x.y.lastName", is(..)).

          body("x.y.age", is(..)).

          body("x.y.gender", is(..));

 

you can use a root and do:

 RestAssured.rootPath = "x.y";

 get(..).then().assertThat().

          body("firstName", is(..)).

          body("lastName", is(..)).

          body("age", is(..)).

          body("gender", is(..)).

 

·         requestSpecification

public static RequestSpecification requestSpecification

Specify a default request specification that will be sent with each request. E,g.

 RestAssured.requestSpecification = new RequestSpecBuilder().addParameter("parameter1", "value1").build();

 

means that for each request by Rest Assured "parameter1" will be equal to "value1".

·         defaultParser

public static Parser defaultParser

Specify a default parser. This parser will be used if the response content-type doesn't match any pre-registered or custom registered parsers. Also useful if the response doesn't contain a content-type at all.

·         responseSpecification

public static ResponseSpecification responseSpecification

Specify a default response specification that will be sent with each request. E,g.

 RestAssured.responseSpecification = new ResponseSpecBuilder().expectStatusCode(200).build();

 

means that for each response Rest Assured will assert that the status code is equal to 200.

·         sessionId

public static String sessionId

Set the default session id value that'll be used for each request. This value will be set in the SessionConfig so it'll override the session id value previously defined there (if any). If you need to change the sessionId cookie name you need to configure and supply the SessionConfig to RestAssured.config.

·         proxy

public static ProxySpecification proxy

Specify a default proxy that REST Assured will use for all requests (unless overridden by individual tests). For example:

 RestAssured.proxy = host("127.0.0.1").withPort(8888);

 

where host is statically imported from ProxySpecification.host(String).

See Also:

proxy(String), proxy(String, int), proxy(String, int, String), proxy(java.net.URI), proxy(ProxySpecification)

·         Constructor Detail

·         RestAssured

public RestAssured()

·         Method Detail

·         filters

public static void filters(List<Filter> filters)

Add default filters that will be applied to each request.

Parameters:

filters - The filter list

·         filters

·         public static void filters(Filter filter,

                           Filter... additionalFilters)

Add default filters to apply to each request.

Parameters:

filter - The filter to add

additionalFilters - An optional array of additional filters to add

·         replaceFiltersWith

public static void replaceFiltersWith(List<Filter> filters)

Sets the default filters to apply to each request.

Parameters:

filters - The filter list

·         replaceFiltersWith

·         public static void replaceFiltersWith(Filter filter,

                                      Filter... additionalFilters)

Sets the default filters to apply to each request.

Parameters:

filter - The filter to set

additionalFilters - An optional array of additional filters to set

·         filters

public static List<Filter> filters()

Returns:

The current default filters

·         objectMapper

public static void objectMapper(ObjectMapper objectMapper)

Set a object mapper that'll be used when serializing and deserializing Java objects to and from it's document representation (XML, JSON etc).

Parameters:

objectMapper - The object mapper to use.

·         expect

public static ResponseSpecification expect()

Start building the response part of the test io.restassured.specification. E.g.

 expect().body("lotto.lottoId", equalTo(5)).when().get("/lotto");

 

will expect that the response body for the GET request to "/lotto" should contain JSON or XML which has a lottoId equal to 5.

Returns:

A response io.restassured.specification.

·         with

public static RequestSpecification with()

Start building the request part of the test io.restassured.specification. E.g.

 with().parameters("firstName", "John", "lastName", "Doe").when().post("/greetXML").then().assertThat().body("greeting.firstName", equalTo("John"));

 

will send a POST request to "/greetXML" with request parameters firstName=John and lastName=Doe and expect that the response body containing JSON or XML firstName equal to John.

The only difference between with() and given() is syntactical.

Returns:

A request specification.

·         withArguments

·         @Deprecated

·         public static List<Argument> withArguments(Object firstArgument,

                                                       Object... additionalArguments)

Deprecated. Use withArgs(Object, Object...) instead

Create a list of arguments that can be used to create parts of the path in a body/content expression. This is useful in situations where you have e.g. pre-defined variables that constitutes the key. For example:

 String someSubPath = "else";

 int index = 1;

 expect().body("something.%s[%d]", withArgs(someSubPath, index), equalTo("some value")). ..

 

or if you have complex root paths and don't wish to duplicate the path for small variations:

 get("/x").then().assertThat().

          root("filters.filterConfig[%d].filterConfigGroups.find { it.name == 'Gold' }.includes").

          body(withArgs(0), hasItem("first")).

          body(withArgs(1), hasItem("second")).

          ..

 

The key and arguments follows the standard formatting syntax of Java.

Returns:

A list of arguments that can be used to build up the response specification

·         withNoArguments

·         @Deprecated

public static List<Argument> withNoArguments()

Deprecated. Use withNoArgs() instead

Create a list of no arguments that can be used to create parts of the path in a response specification for JSON, XML or HTML validation. This is useful in situations where you have e.g. pre-defined variables that constitutes the key. For example:

 get("/jsonStore").then().

          root("store.%s", withArgs("book")).

          body("category.size()", equalTo(4)).

          appendRoot("%s.%s", withArgs("author", "size()")).

          body(withNoArguments(), equalTo(4));

 

Returns:

A list of no arguments that can be used to build up the response specification

·         withArgs

·         public static List<Argument> withArgs(Object firstArgument,

                                      Object... additionalArguments)

Create a list of arguments that can be used to create parts of the path in a body/content expression. This is useful in situations where you have e.g. pre-defined variables that constitutes the key. For example:

 String someSubPath = "else";

 int index = 1;

 when().get().then().body("something.%s[%d]", withArgs(someSubPath, index), equalTo("some value")). ..

 

or if you have complex root paths and don't wish to duplicate the path for small variations:

 get("/x").then().assertThat().

          root("filters.filterConfig[%d].filterConfigGroups.find { it.name == 'Gold' }.includes").

          body(withArgs(0), hasItem("first")).

          body(withArgs(1), hasItem("second")).

          ..

 

The key and arguments follows the standard formatting syntax of Java.

Returns:

A list of arguments.

·         withNoArgs

public static List<Argument> withNoArgs()

Create a list of no arguments that can be used to create parts of the path in a response specification for JSON, XML or HTML validation. This is useful in situations where you have e.g. pre-defined variables that constitutes the key. For example:

 get("/jsonStore").then().

          root("store.%s", withArgs("book")).

          body("category.size()", equalTo(4)).

          appendRoot("%s.%s", withArgs("author", "size()")).

          body(withNoArgs(), equalTo(4));

Returns:

A list of no arguments.

·         given

public static RequestSpecification given()

Start building the request part of the test io.restassured.specification. E.g.

 given().parameters("firstName", "John", "lastName", "Doe").when().post("/greetXML").then().body("greeting.firstName", equalTo("John"));

 

will send a POST request to "/greetXML" with request parameters firstName=John and lastName=Doe and expect that the response body containing JSON or XML firstName equal to John.

The only difference between with() and given() is syntactical.

Returns:

A request specification.

·         when

public static RequestSender when()

Start building the DSL expression by sending a request without any parameters or headers etc. E.g.

 when().

        get("/x").

 then().

        body("x.y.z1", equalTo("Z1")).

        body("x.y.z2", equalTo("Z2"));

 

Note that if you need to add parameters, headers, cookies or other request properties use the given() method.

Returns:

A request sender interface that let's you call resources on the server

·         given

·         public static RequestSender given(RequestSpecification requestSpecification,

                                  ResponseSpecification responseSpecification)

When you have long specifications it can be better to split up the definition of response and request specifications in multiple lines. You can then pass the response and request specifications to this method. E.g.

 RequestSpecification requestSpecification = with().parameters("firstName", "John", "lastName", "Doe");

 ResponseSpecification responseSpecification = expect().body("greeting", equalTo("Greetings John Doe"));

 given(requestSpecification, responseSpecification).get("/greet");

 

This will perform a GET request to "/greet" and verify it according to the responseSpecification.

Returns:

A test io.restassured.specification.

·         given

public static RequestSpecification given(RequestSpecification requestSpecification)

When you're only interested in supplying a predefined request specification without a response specification then you can use this method. For example:

 RequestSpecification requestSpecification = with().parameters("firstName", "John", "lastName", "Doe");

 given(requestSpecification).get("/greet"). ..;

 

This will perform a GET request to "/greet" and without any validation (only a static response specification has been configured).

Returns:

A RequestSender

·         get

·         public static Response get(String path,

                           Object... pathParams)

Perform a GET request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:

path - The path to send the request to.

pathParams - The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do get("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);.

Returns:

The response of the GET request.

·         get

·         public static Response get(String path,

                           Map<String,?> pathParams)

Perform a GET request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:

path - The path to send the request to.

pathParams - The path parameters.

Returns:

The response of the GET request.

·         post

·         public static Response post(String path,

                            Object... pathParams)

Perform a POST request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:

path - The path to send the request to.

pathParams - The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do post("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);.

Returns:

The response of the request.

·         post

·         public static Response post(String path,

                            Map<String,?> pathParams)

Perform a POST request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:

path - The path to send the request to.

pathParams - The path parameters.

Returns:

The response of the request.

·         put

·         public static Response put(String path,

                           Object... pathParams)

Perform a PUT request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:

path - The path to send the request to.

pathParams - The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do put("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);.

Returns:

The response of the request.

·         delete

·         public static Response delete(String path,

                              Object... pathParams)

Perform a DELETE request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:

path - The path to send the request to.

pathParams - The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do delete("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);.

Returns:

The response of the request.

·         delete

·         public static Response delete(String path,

                              Map<String,?> pathParams)

Perform a DELETE request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:

path - The path to send the request to.

pathParams - The path parameters.

Returns:

The response of the request.

·         head

·         public static Response head(String path,

                            Object... pathParams)

Perform a HEAD request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:

path - The path to send the request to.

pathParams - The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do head("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);.

Returns:

The response of the request.

·         head

·         public static Response head(String path,

                            Map<String,?> pathParams)

Perform a HEAD request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:

path - The path to send the request to.

pathParams - The path parameters.

Returns:

The response of the request.

·         patch

·         public static Response patch(String path,

                             Object... pathParams)

Perform a PATCH request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:

path - The path to send the request to.

pathParams - The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do head("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);.

Returns:

The response of the request.

·         patch

·         public static Response patch(String path,

                             Map<String,?> pathParams)

Perform a PATCH request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:

path - The path to send the request to.

pathParams - The path parameters.

Returns:

The response of the request.

·         options

·         public static Response options(String path,

                               Object... pathParams)

Perform a OPTIONS request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:

path - The path to send the request to.

pathParams - The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do head("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);.

Returns:

The response of the request.

·         options

·         public static Response options(String path,

                               Map<String,?> pathParams)

Perform a OPTIONS request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:

path - The path to send the request to.

pathParams - The path parameters.

Returns:

The response of the request.

·         get

public static Response get(URI uri)

Perform a GET request to a uri.

Parameters:

uri - The uri to send the request to.

Returns:

The response of the GET request.

·         post

public static Response post(URI uri)

Perform a POST request to a uri.

Parameters:

uri - The uri to send the request to.

Returns:

The response of the request.

·         put

public static Response put(URI uri)

Perform a PUT request to a uri.

Parameters:

uri - The uri to send the request to.

Returns:

The response of the request.

·         delete

public static Response delete(URI uri)

Perform a DELETE request to a uri.

Parameters:

uri - The uri to send the request to.

Returns:

The response of the request.

·         head

public static Response head(URI uri)

Perform a HEAD request to a uri.

Parameters:

uri - The uri to send the request to.

Returns:

The response of the request.

·         patch

public static Response patch(URI uri)

Perform a PATCH request to a uri.

Parameters:

uri - The uri to send the request to.

Returns:

The response of the request.

·         options

public static Response options(URI uri)

Perform a OPTIONS request to a uri.

Parameters:

uri - The uri to send the request to.

Returns:

The response of the request.

·         get

public static Response get(URL url)

Perform a GET request to a url.

Parameters:

url - The url to send the request to.

Returns:

The response of the GET request.

·         post

public static Response post(URL url)

Perform a POST request to a url.

Parameters:

url - The url to send the request to.

Returns:

The response of the request.

·         put

public static Response put(URL url)

Perform a PUT request to a url.

Parameters:

url - The url to send the request to.

Returns:

The response of the request.

·         delete

public static Response delete(URL url)

Perform a DELETE request to a url.

Parameters:

url - The url to send the request to.

Returns:

The response of the request.

·         head

public static Response head(URL url)

Perform a HEAD request to a url.

Parameters:

url - The url to send the request to.

Returns:

The response of the request.

·         patch

public static Response patch(URL url)

Perform a PATCH request to a url.

Parameters:

url - The url to send the request to.

Returns:

The response of the request.

·         options

public static Response options(URL url)

Perform a OPTIONS request to a url.

Parameters:

url - The url to send the request to.

Returns:

The response of the request.

·         get

public static Response get()

Perform a GET request to the statically configured path (by default http://localhost:8080).

Returns:

The response of the GET request.

·         post

public static Response post()

Perform a POST request to the statically configured path (by default http://localhost:8080).

Returns:

The response of the request.

·         put

public static Response put()

Perform a PUT request to the statically configured path (by default http://localhost:8080).

Returns:

The response of the request.

·         delete

public static Response delete()

Perform a DELETE request to the statically configured path (by default http://localhost:8080).

Returns:

The response of the request.

·         head

public static Response head()

Perform a HEAD request to the statically configured path (by default http://localhost:8080).

Returns:

The response of the request.

·         patch

public static Response patch()

Perform a PATCH request to the statically configured path (by default http://localhost:8080).

Returns:

The response of the request.

·         options

public static Response options()

Perform a OPTIONS request to the statically configured path (by default http://localhost:8080).

Returns:

The response of the request.

·         request

public static Response request(Method method)

Perform a request to the pre-configured path (by default http://localhost:8080).

Parameters:

method - The HTTP method to use

Returns:

The response of the request.

·         request

public static Response request(String method)

Perform a custom HTTP request to the pre-configured path (by default http://localhost:8080).

Parameters:

method - The HTTP method to use

Returns:

The response of the request.

·         request

·         public static Response request(Method method,

·                                        String path,

                               Object... pathParams)

Perform a HTTP request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:

method - The HTTP method to use

path - The path to send the request to.

pathParams - The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do request(Method.TRACE,"/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);.

Returns:

The response of the request.

·         request

·         public static Response request(String method,

·                                        String path,

                               Object... pathParams)

Perform a custom HTTP request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to specify the path as http://localhost:8080/path. In this case it's enough to use /path.

Parameters:

method - The HTTP method to use

path - The path to send the request to.

pathParams - The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do request("method","/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);.

Returns:

The response of the request.

·         request

·         public static Response request(Method method,

                               URI uri)

Perform a request to a uri.

Parameters:

method - The HTTP method to use

uri - The uri to send the request to.

Returns:

The response of the GET request.

·         request

·         public static Response request(Method method,

                               URL url)

Perform a request to a url.

Parameters:

method - The HTTP method to use

url - The url to send the request to.

Returns:

The response of the GET request.

·         request

·         public static Response request(String method,

                               URI uri)

Perform a custom HTTP request to a uri.

Parameters:

method - The HTTP method to use

uri - The uri to send the request to.

Returns:

The response of the GET request.

·         request

·         public static Response request(String method,

                               URL url)

Perform a custom HTTP request to a url.

Parameters:

method - The HTTP method to use

url - The url to send the request to.

Returns:

The response of the GET request.

·         basic

·         public static AuthenticationScheme basic(String userName,

                                         String password)

Create a http basic authentication scheme.

Parameters:

userName - The user name.

password - The password.

Returns:

The authentication scheme

·         form

·         public static AuthenticationScheme form(String userName,

                                        String password)

Use form authentication. Rest Assured will try to parse the response login page and determine and try find the action, username and password input field automatically.

Note that the request will be much faster if you also supply a form auth configuration.

Parameters:

userName - The user name.

password - The password.

Returns:

The authentication scheme

See Also:

form(String, String, FormAuthConfig)

·         form

·         public static AuthenticationScheme form(String userName,

·                                                 String password,

                                        FormAuthConfig config)

Use form authentication with the supplied configuration.

Parameters:

userName - The user name.

password - The password.

config - The form authentication config

Returns:

The authentication scheme

·         preemptive

public static PreemptiveAuthProvider preemptive()

Return the http preemptive authentication specification for setting up preemptive authentication requests. This means that the authentication details are sent in the request header regardless if the server challenged for authentication or not.

Returns:

The authentication scheme

·         certificate

·         public static AuthenticationScheme certificate(String certURL,

                                               String password)

Sets a certificate to be used for SSL authentication. See Class.getResource(String) for how to get a URL from a resource on the classpath.

Uses SSL settings defined in SSLConfig.

Parameters:

certURL - URL to a JKS keystore where the certificate is stored.

password - The password for the keystore

Returns:

The request io.restassured.specification

·         certificate

·         public static AuthenticationScheme certificate(String certURL,

·                                                        String password,

                                               CertificateAuthSettings certificateAuthSettings)

Sets a certificate to be used for SSL authentication. See Class.getResource(String) for how to get a URL from a resource on the classpath.

Parameters:

certURL - URL to a JKS keystore where the certificate is stored.

password - The password for the keystore

certificateAuthSettings - More advanced settings for the certificate authentication

·         certificate

·         public static AuthenticationScheme certificate(String trustStorePath,

·                                                        String trustStorePassword,

·                                                        String keyStorePath,

·                                                        String keyStorePassword,

                                               CertificateAuthSettings certificateAuthSettings)

Sets a certificate to be used for SSL authentication. See Class.getResource(String) for how to get a URL from a resource on the classpath.

Parameters:

trustStorePath - URL to a JKS trust store where the certificate is stored.

trustStorePassword - The password for the trust store

keyStorePath - URL to a JKS keystore where the certificate is stored.

keyStorePassword - The password for the keystore

certificateAuthSettings - More advanced settings for the certificate authentication

·         digest

·         public static AuthenticationScheme digest(String userName,

                                          String password)

Use http digest authentication. Note that you need to encode the password yourself.

Parameters:

userName - The user name.

password - The password.

Returns:

The authentication scheme

·         oauth

·         public static AuthenticationScheme oauth(String consumerKey,

·                                                  String consumerSecret,

·                                                  String accessToken,

                                         String secretToken)

Excerpt from the HttpBuilder docs:
OAuth sign the request. Note that this currently does not wait for a WWW-Authenticate challenge before sending the the OAuth header. All requests to all domains will be signed for this instance. This assumes you've already generated an accessToken and secretToken for the site you're targeting. For More information on how to achieve this, see the Signpost documentation.

Parameters:

consumerKey -

consumerSecret -

accessToken -

secretToken -

Returns:

The authentication scheme

·         oauth

·         public static AuthenticationScheme oauth(String consumerKey,

·                                                  String consumerSecret,

·                                                  String accessToken,

·                                                  String secretToken,

                                         OAuthSignature signature)

Excerpt from the HttpBuilder docs:
OAuth sign the request. Note that this currently does not wait for a WWW-Authenticate challenge before sending the the OAuth header. All requests to all domains will be signed for this instance. This assumes you've already generated an accessToken and secretToken for the site you're targeting. For More information on how to achieve this, see the Signpost documentation.

Parameters:

consumerKey -

consumerSecret -

accessToken -

secretToken -

signature -

Returns:

The authentication scheme

·         oauth2

public static AuthenticationScheme oauth2(String accessToken)

OAuth sign the request. Note that this currently does not wait for a WWW-Authenticate challenge before sending the the OAuth header. All requests to all domains will be signed for this instance.

Parameters:

accessToken - The access token to use

Returns:

The authentication scheme

·         oauth2

·         public static AuthenticationScheme oauth2(String accessToken,

                                          OAuthSignature signature)

OAuth sign the request. Note that this currently does not wait for a WWW-Authenticate challenge before sending the the OAuth header. All requests to all domains will be signed for this instance.

Parameters:

accessToken -

signature -

Returns:

The authentication scheme

·         registerParser

·         public static void registerParser(String contentType,

                                  Parser parser)

Register a custom content-type to be parsed using a predefined parser. E.g. let's say you want parse content-type application/custom with the XML parser to be able to verify the response using the XML dot notations:

 get("/x").then().assertThat().body("document.child", equalsTo("something"))..

 

Since application/custom is not registered to be processed by the XML parser by default you need to explicitly tell REST Assured to use this parser before making the request:

 RestAssured.registerParser("application/custom, Parser.XML");

 

Parameters:

contentType - The content-type to register

parser - The parser to use when verifying the response.

·         unregisterParser

public static void unregisterParser(String contentType)

Unregister the parser associated with the provided content-type

Parameters:

contentType - The content-type associated with the parser to unregister.

·         reset

public static void reset()

Resets the baseURI, basePath, port, authentication and rootPath, filters(java.util.List), requestSpecification, responseSpecification, urlEncodingEnabled, config, sessionId and proxy to their default values of "http://localhost", "", -1, no authentication, <empty string>, null, null, <empty list>, null, null, none, true, new RestAssuredConfig(), null and null.

·         useRelaxedHTTPSValidation

public static void useRelaxedHTTPSValidation()

Use relaxed HTTP validation with protocol . This means that you'll trust all hosts regardless if the SSL certificate is invalid. By using this method you don't need to specify a keystore (see keyStore(String, String) or trust store (see trustStore(java.security.KeyStore).

This is just a shortcut for:

 RestAssured.config = RestAssured.config().sslConfig(sslConfig().relaxedHTTPSValidation());

 

·         useRelaxedHTTPSValidation

public static void useRelaxedHTTPSValidation(String protocol)

Use relaxed HTTP validation with a specific protocol. This means that you'll trust all hosts regardless if the SSL certificate is invalid. By using this method you don't need to specify a keystore (see keyStore(String, String) or trust store (see trustStore(java.security.KeyStore).

This is just a shortcut for:

 RestAssured.config = RestAssured.config().sslConfig(sslConfig().relaxedHTTPSValidation(<protocol>));

 

Parameters:

protocol - The standard name of the requested protocol. See the SSLContext section in the Java Cryptography Architecture Standard Algorithm Name Documentation for information about standard protocol names.

·         enableLoggingOfRequestAndResponseIfValidationFails

public static void enableLoggingOfRequestAndResponseIfValidationFails()

Enable logging of both the request and the response if REST Assureds test validation fails with log detail equal to LogDetail.ALL.

This is just a shortcut for:

 RestAssured.config = RestAssured.config().logConfig(logConfig().enableLoggingOfRequestAndResponseIfValidationFails());

 

·         enableLoggingOfRequestAndResponseIfValidationFails

public static void enableLoggingOfRequestAndResponseIfValidationFails(LogDetail logDetail)

Enable logging of both the request and the response if REST Assureds test validation fails with the specified log detail.

This is just a shortcut for:

 RestAssured.config = RestAssured.config().logConfig(logConfig().enableLoggingOfRequestAndResponseIfValidationFails(logDetail));

 

Parameters:

logDetail - The log detail to show in the log

·         keyStore

·         public static void keyStore(String pathToJks,

                            String password)

Apply a keystore for all requests

 given().keyStore("/truststore_javanet.jks", "test1234"). ..

 

Note that this is just a shortcut for:

 RestAssured.config = RestAssured.config().sslConfig(sslConfig().keyStore(pathToJks, password));

 

Parameters:

pathToJks - The path to the JKS. REST Assured will first look in the classpath and if not found it will look for the JKS in the local file-system

password - The store pass

·         trustStore

·         public static void trustStore(String pathToJks,

                              String password)

The following documentation is taken from https://github.com/jgritman/httpbuilder/wiki/SSL:

SSL Configuration

SSL should, for the most part, "just work." There are a few situations where it is not completely intuitive. You can follow the example below, or see HttpClient's SSLSocketFactory documentation for more information.

SSLPeerUnverifiedException

If you can't connect to an SSL website, it is likely because the certificate chain is not trusted. This is an Apache HttpClient issue, but explained here for convenience. To correct the untrusted certificate, you need to import a certificate into an SSL truststore.

First, export a certificate from the website using your browser. For example, if you go to https://dev.java.net in Firefox, you will probably get a warning in your browser. Choose "Add Exception," "Get Certificate," "View," "Details tab." Choose a certificate in the chain and export it as a PEM file. You can view the details of the exported certificate like so:

 $ keytool -printcert -file EquifaxSecureGlobaleBusinessCA-1.crt

 Owner: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US

 Issuer: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US

 Serial number: 1

 Valid from: Mon Jun 21 00:00:00 EDT 1999 until: Sun Jun 21 00:00:00 EDT 2020

 Certificate fingerprints:

 MD5:  8F:5D:77:06:27:C4:98:3C:5B:93:78:E7:D7:7D:9B:CC

 SHA1: 7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45

 Signature algorithm name: MD5withRSA

 Version: 3

 ....

 

Now, import that into a Java keystore file:

 $ keytool -importcert -alias "equifax-ca" -file EquifaxSecureGlobaleBusinessCA-1.crt -keystore truststore_javanet.jks -storepass test1234

 Owner: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US

 Issuer: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US

 Serial number: 1

 Valid from: Mon Jun 21 00:00:00 EDT 1999 until: Sun Jun 21 00:00:00 EDT 2020

 Certificate fingerprints:

 MD5:  8F:5D:77:06:27:C4:98:3C:5B:93:78:E7:D7:7D:9B:CC

 SHA1: 7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45

 Signature algorithm name: MD5withRSA

 Version: 3

 ...

 Trust this certificate? [no]:  yes

 Certificate was added to keystore

 

Now you want to use this truststore in your client:

 RestAssured.trustSture("/truststore_javanet.jks", "test1234");

 

or

 given().trustStore("/truststore_javanet.jks", "test1234"). ..

 

Note that this is just a shortcut for:

 RestAssured.config = RestAssured.config().sslConfig(sslConfig().trustStore(pathToJks, password));

 

Parameters:

pathToJks - The path to the JKS. REST Assured will first look in the classpath and if not found it will look for the JKS in the local file-system

password - The store pass

·         trustStore

public static void trustStore(KeyStore truststore)

Specify a trust store that'll be used for HTTPS requests. A trust store is a KeyStore that has been loaded with the password. If you wish that REST Assured loads the KeyStore store and applies the password (thus making it a trust store) please see some of the keystore methods such as keyStore(java.io.File, String).

Parameters:

truststore - A pre-loaded KeyStore.

See Also:

keyStore(String, String)

·         keyStore

·         public static void keyStore(File pathToJks,

                            String password)

Use a keystore located on the file-system. See keyStore(String, String) for more details. *

Note that this is just a shortcut for:

 RestAssured.config = RestAssured.config().sslConfig(sslConfig().keyStore(pathToJks, password));

 

Parameters:

pathToJks - The path to JKS file on the file-system

password - The password for the keystore

See Also:

keyStore(String, String)

·         trustStore

·         public static void trustStore(File pathToJks,

                              String password)

Use a trust store located on the file-system. See trustStore(String, String) for more details. *

Note that this is just a shortcut for:

 RestAssured.config = RestAssured.config().sslConfig(sslConfig().trustStore(pathToJks, password));

 

Parameters:

pathToJks - The path to JKS file on the file-system

password - The password for the keystore

See Also:

keyStore(String, String)

·         keyStore

public static void keyStore(String password)

Uses the user default keystore stored in @{user.home}/.keystore *

Note that this is just a shortcut for:

 RestAssured.config = RestAssured.config().sslConfig(sslConfig().keyStore(password));

 

Parameters:

password - - Use null for no password

·         proxy

·         public static void proxy(String host,

                         int port)

Instruct REST Assured to connect to a proxy on the specified host and port.

Parameters:

host - The hostname of the proxy to connect to (for example 127.0.0.1)

port - The port of the proxy to connect to (for example 8888)

·         proxy

public static void proxy(String host)

Instruct REST Assured to connect to a proxy on the specified host on port 8888.

Parameters:

host - The hostname of the proxy to connect to (for example 127.0.0.1). Can also be a URI represented as a String.

See Also:

proxy(String, int)

·         proxy

public static void proxy(int port)

Instruct REST Assured to connect to a proxy on the specified port on localhost.

Parameters:

port - The port of the proxy to connect to (for example 8888)

See Also:

proxy(String, int)

·         proxy

·         public static void proxy(String host,

·                                  int port,

                         String scheme)

Instruct REST Assured to connect to a proxy on the specified port on localhost with a specific scheme.

Parameters:

host - The hostname of the proxy to connect to (for example 127.0.0.1)

port - The port of the proxy to connect to (for example 8888)

scheme - The http scheme (http or https)

·         proxy

public static void proxy(URI uri)

Instruct REST Assured to connect to a proxy using a URI.

Parameters:

uri - The URI of the proxy

·         proxy

public static void proxy(ProxySpecification proxySpecification)

Instruct REST Assured to connect to a proxy using a ProxySpecification.

Parameters:

proxySpecification - The proxy specification to use.

See Also:

RequestSpecification.proxy(ProxySpecification)

·         config

public static RestAssuredConfig config()

Returns:

The assigned config or a new config is no config is assigned

展开阅读全文
打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部