1

I'm new to JMeter. I've a Java code which I've imported as JAR file. There is a variable called output, in which the result is in which the output is received and is printed. I want to access that variable from Jmeter Beanshell. Can anyone help me out with that?

My Java code is as follows:

package co.in;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class RestClientGet_Validate {

    // http://localhost:8080/RESTfulExample/json/product/get
    public static void main(String[] args) {

      try {

        URL url = new URL("http://172.16.2.192:8080/pivot_service_1.0/service/validate");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            response = output;
        }

        conn.disconnect();

      } catch (MalformedURLException e) {

        e.printStackTrace();

      } catch (IOException e) {

        e.printStackTrace();

      }
    }
}
Electronic Brat
  • 133
  • 1
  • 2
  • 11

1 Answers1

0

First of all, be informed that you can execute the request using JMeter's HTTP Request sampler and obtain the output using Regular Expression Extractor


If you're looking for a way to re-use your existing Java code in JMeter scripting test elements:

  1. You need to change return type of your function to String, to wit replace

    public static void main(String[] args)
    

    with

    public static String main()
    
    1. You need to add return statement at the end of your function like:

      return output;

    2. Once done place the .jar to JMeter Classpath and restart JMeter to pick it up

    3. If everything goes well you should be able to access the value in Beanshell like:

      String output = co.in.RestClientGet_Validate.main();

Also be aware that starting from JMeter 3.1 it is recommended to switch to JSR223 Test Elements and Groovy language for scripting so consider migrating from Beanshell ASAP.

Dmitri T
  • 159,985
  • 5
  • 83
  • 133