如何捕获 Bean shell 采样器的响应

How to capture response of a Bean shell sampler

以上是我编写的代码,用于访问其端点需要字节流对象的 Web 服务。 我能够做到这一点,但我没有得到任何回应。 我必须测试响应。 虽然我得到 200 ok,但是发送了一个字符串作为我没有得到的响应。

并且响应为空白

我怎样才能得到回复?

您可以使用 SampleResult 对象添加输出:

String output = "...";

SampleResult.setResponseData( output );
SampleResult.setDataType( org.apache.jmeter.samplers.SampleResult.TEXT );
  1. 为了读取服务器的响应,您需要使用 URLConnection.getInputStream() method,而不是 OutputStream
  2. 为了将流转换为字符串,您可以使用 IOUtils.toString() method
  3. 为了return数据你可以使用return keyword
  4. 下面是最基本的工作代码,请根据您的需要进行调整:

    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.nio.charset.StandardCharsets;
    import org.apache.commons.io.IOUtils;
    
    URL url = new URL("http://example.com");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    String response = IOUtils.toString(con.getInputStream(), StandardCharsets.UTF_8);
    return response;