我有一个使用Maven构建的Spring Boot应用。现在,我计划从此应用程序向SOAP服务发出请求。 SOAP服务由WSDL定义。我可以使用这种方法发出请求并获得响应:
private String makeSoapRequest(String request, String action) throws IOException {
URL url = new URL("http://localhost/");
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection)urlConnection;
InputStream is = new ByteArrayInputStream(request.getBytes());
baos = new ByteArrayOutputStream();
copy(is, baos);
is.close();
byte[] bytes = baos.toByteArray();
httpURLConnection.setRequestProperty("Content-Length", String.valueOf( bytes.length ) );
httpURLConnection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpURLConnection.setRequestProperty("SOAPAction", action);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream out = httpURLConnection.getOutputStream();
out.write(bytes);
out.close();
InputStreamReader isr = new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader in = new BufferedReader(isr);
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
ab.append(inputLine);
}
return sb.ToString();
}
但是,我的请求和响应是XML字符串。如何从WSDL生成请求和响应类,以便可以使用它们通过HttpURLConnection
发出请求?
使用Apache CXF没有帮助,因为我应该使用HttpURLConnection
。这是已使用服务的要求之一。
我可以使用JAXB或JAX-WS生成类,但是将生成的适当类作为请求正文发送给我400 Bad Request错误。
您应该使用代码生成器。您可以在CXF文档中找到有关WSDL2Java的更多信息:https://cxf.apache.org/docs/how-do-i-develop-a-client.html