JMeter AJAX example

I couldn’t find any complete AJAX examples. Most of them, including the one on blazemeter.com that provided the impetus for this post, don’t go far enough to include the cookies needed for the requests to work in most web application contexts.

This was an exercise in patience. I tried many iterations of CookieManager, BasicCookieStore, etc., and none seemed to properly persist the values to the request. Much code has been removed from what is below, including things such as HttpContext, etc., that were passed to the HttpResponse call with the proper CookieStore attached. Regardless, I ended up handcoding a copy of the cookies from the previous request and did a manual setHeader, as shown below. This works!

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult;
import org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy;
import org.apache.jmeter.protocol.http.control.Cookie;
import org.apache.jmeter.protocol.http.control.CookieManager;

import java.util.*;
import java.util.concurrent.*;
      
List urls = new ArrayList();
Collections.addAll(urls,args);
ExecutorService pool = Executors.newFixedThreadPool(urls.size()); 

HTTPSamplerProxy previousSampler = ctx.getPreviousSampler();
CookieManager manager = previousSampler.getCookieManager();
String cookies = "";

for (int i = 0; i < manager.getCookieCount(); i++) {
  Cookie cookie = manager.get(i);        
  cookies += cookie.getName() + "=" + cookie.getValue() + ";";
  out.println(cookie);
}

out.println(cookies);

for (String url : urls) {
   final String currentURL = url;
   pool.submit(new Runnable() {
     @Override
     public void run() {
       try {
         System.out.println("getting " + currentURL);

         HttpClient httpclient = new DefaultHttpClient();
         HttpGet httpget = new HttpGet(currentURL);
         httpget.setHeader("X-Requested-With", "XMLHttpRequest");
         httpget.setHeader("Cookie", cookies);
         System.out.println("executing request " + httpget.getURI());
         HttpResponse response = httpclient.execute(httpget);
         System.out.println(currentURL + " " + response.toString());
         HttpEntity entity = response.getEntity();
         EntityUtils.consume(entity);
       } 
       catch (Exception ex) {
         ex.printStackTrace();
       }
     }
   });
}
pool.shutdown();

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.