2

I am using Selenium with Java.

I am trying to verify that a specific third party request came in so in order to capture the network traffic I used a proxy named BrowserMobProxy. I wrote the content of the request into a HAR like this:

proxy.newHar("Something");
Har har = proxy.getHar();
try {
    har.writeTo(new File("Blah.json"));
} catch (IOException e) {
    e.printStackTrace();
}

My question is,

instead of having to write into a file,

  • in order to verify that a specific request came in
  • is there a more concise way to do this similar to proxy.getHar().contains("whatever you are searching for... ")?

2 Answers 2

2

(Disclaimer, I didn't test this. It may not work as is, but hopefully will at least give you an idea about a possible solution)

You could try something like:

Har har = proxy.getHar();
ByteArrayOutputStream out = new ByteArrayOutputStream();

try {
    har.writeTo(out);
} catch (IOException e) {
    e.printStackTrace();
}

InputStream in = new ByteArrayInputStream(out.toByteArray());

org.json.JSONObject json = new org.json.JSONObject(org.apache.commons.io.IOUtils.toString(in));

This solution would require the apache commons library and the org.json library, so definitely not possible with vanilla java. But this puts your json into an object that will let you parse through the data without needing to write it to a file as long as it's in standard format.

The idea behind this solution is that instead of writing the har to a file directly. You may write it to an output stream. This output stream can either be written out somewhere, or fed into a receiving input stream that can then turn it into a String. Once it's a string, you can do whatever you want with it! The org.json library is simply my personal choice since it's always worked well with my needs.

1
  • Awesome, thanks! I used IOUtils.toString(in) instead of the json object.
    – Robben
    Jul 12, 2016 at 13:55
2

You can access a logged entry from Har object at runtime. For instance, the following code will return only entries (tuples of a request and a response) with HTTP POST request:

Har har = proxy.getHar();
List<HarEntry> matchingEntries = har.getLog().getEntries().stream()
  .filter(e -> e.getRequest().getMethod().equals("POST"))
  .collect(Collectors.toList());

You can find information about Har class in JavaDoc.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.