我在SoapUI中创建了一个模拟服务。我在这个模拟服务中使用Groovy,这样我就可以模拟一些请求,以及将其他请求转发到我正在模拟的实际Web服务。当Web服务返回三个可能的故障消息之一时,我无法从肥皂响应中检索到实际故障。
模拟服务Groovy脚本只是回复下面的响应(IOException,超文本传输协议状态500)。但是当直接向实际的Web服务发送请求时,我得到了我真正想要得到的响应。
转发请求并检索响应的Groovy代码:
def soapUrl = new URL("[actual web service]");
def connection = soapUrl.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type" ,"text/html");
connection.setRequestProperty("SOAPAction", "");
connection.doOutput = true;
Writer writer = new OutputStreamWriter(connection.outputStream);
writer.write(soapRequest);
writer.flush();
writer.close();
connection.connect();
def soapResponse = connection.content.text;
// alert.showInfoMessage(soapResponse);
requestContext.responseMessage = soapResponse;
使用Groovy脚本模拟服务的响应:
<soapenv:Body>
<soapenv:Fault>
<faultcode>Server</faultcode>
<faultstring>Failed to dispatch using script; java.io.IOException: Server returned HTTP response code: 500 for URL: [the endpoint url]</faultstring>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>
直接访问Web服务时的响应(使用相同的请求):
<soapenv:Body>
<soapenv:Fault>
<faultcode>soapenv:Server</faultcode>
<faultstring> [actual fault message] </faultstring>
<detail> [useful details about the fault] </detail>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>
使用脚本时,为什么响应与我直接检索它不同?
好的,我发现我可以以不同的方式使用连接(URLConnection)。我根据这里接受的答案做了一些更改。现在,实际的响应,快乐或错误,被检索。所以在这两种情况下,Web服务响应都被转发到模拟服务输出。现在我可以在响应中看到故障信息。
...
connection.connect();
// Get the response
HttpURLConnection httpConnection = (HttpURLConnection) connection;
InputStream is;
if (httpConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
is = httpConnection.getInputStream();
} else {
// Http error
is = httpConnection.getErrorStream();
}
// Read from input stream
StringBuilder builder = new StringBuilder();
BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = buffer.readLine()) != null) {
builder.append(line);
}
buffer.close();
// Forward the response to mock service output
requestContext.responseMessage = builder.toString();