Cant extract attribute from html response

Viewed 1083

I am trying to extract an attribute from html response.

<html>
<head></head>
<body>
<script type="text/javascript" src="/sso/js/jquery/1/jquery.min.js?20190218"></script>
{serviceUrl: 'https://abcd/12345', serviceTicket: 'ABCD-123-1271821818sdsdbbsdgw3-pas'}
</body>
</html>

The response for a webservice gives me the above html response from which i wanted to extract value of an serviceUrl attribute but its giving me nullpointer exception . In the below code , res is the html response stored as String.

Response res =  given()
    .queryParam("logintoken", logintoken)
    .when()
    .get("/sso/login")
    .then().assertThat().statusCode(200).extract().response();

Document doc = Jsoup.parse(res.toString());
Element link = doc.select("script").first();
String serviceUrl = link.attr("serviceUrl");
System.out.println(serviceUrl);

I expect the serviceUrl in the last statement to bring me back https://abcd/12345 but it gives me null pointer exception

1 Answers

To get full response body as a string you need to use asString() method instead of toString(). Here's an example:

Response response =  given()
    .queryParam("logintoken", logintoken)
    .when()
    .get("/sso/login")
    .then().assertThat().statusCode(200).extract().response();

//Extract response body as a string
String html = response.asString();

//Parse extracted html with Jsoup
Document document = Jsoup.parse(html);

//Get <body> element from html
Element body = document.body();

//Extract text from <body> element
String bodyText = body.ownText();

//Parse extracted text using Jackson's ObjectMapper
Map<String, Object> map = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();

//Configure Jackson to work with unquoted fields and single quoted values
mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

try {
  map = mapper.readValue(String.valueOf(bodyText), new TypeReference<Map<String, Object>>() {});
} catch (Exception e) {
  e.printStackTrace();
}

System.out.println(map.get("serviceUrl"));

Jackson's ObjectMapper was used in the example above to parse text from <body>. You can read more about it here - https://github.com/FasterXML/jackson-databind

Related