在Java中发送XML报文可以使用以下步骤:
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setDoOutput(true); // 允许向服务器写入数据
connection.setDoInput(true); // 允许从服务器读取数据
connection.setRequestProperty("Content-Type", "application/xml;charset=UTF-8");
String xml = "<xml>...</xml>";
OutputStream outputStream = connection.getOutputStream();
outputStream.write(xml.getBytes("UTF-8"));
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
// 处理响应数据
inputStream.close();
}
connection.disconnect();
上述代码示例了如何发送一个XML报文,并接收服务器的响应。你可以根据实际情况修改其中的URL、XML内容和请求头等。