2012-01-04 58 views
2

我想要查看一个特定的字符串是否存在于一个html页面中,但我似乎无法找到一个简单的方法来获取表示该body的字符串。从groovy的响应中获取html body

我已经尝试:

http.request(Method.GET, { req -> 
     uri.path = '/x/app/main' 
     response.success = { resp, reader -> 
      assert resp.status == 200 
      println reader.text.startsWith('denied') 
     } 

     response.failure = { resp -> 
      fail("Failure reported: ${resp.statusLine}") 
     } 
    }) 

但reader.text是NodeChildren对象。

如何获取html(或更具体地说,身体的上下文)作为一个字符串?

回答

3

您可以直接从响应中获取输入流。试试这个:

http.request(Method.GET, { req -> 
    uri.path = '/x/app/main' 
    response.success = { resp -> 
     assert resp.status == 200 
     println resp.entity.content.text.startsWith('denied') 
    } 

    response.failure = { resp -> 
     fail("Failure reported: ${resp.statusLine}") 
    } 
}) 
+0

尝试过了,得到了错误:java.lang.IllegalStateException:内容已在org.apache.http.entity.BasicHttpEntity.getContent(BasicHttpEntity.java:84)被消耗 \t \t在org.apache.http.conn.BasicManagedEntity.getContent(BasicManagedEntity.java:87) – user965697 2012-01-04 16:28:06

+1

确保你使用了一个'arg'response.success'闭包。如果你使用两个arg版本('response.success = {resp,reader - >'),你会得到这个异常。 – ataylor 2012-01-04 16:36:24

+1

似乎已经做到了!谢谢。问题:有没有好的文档列出响应中的内容?我什至不知道你是怎么想到的:) – user965697 2012-01-04 16:42:27