在Java中發(fā)送XML報文可以使用以下步驟:
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setDoOutput(true); // 允許向服務(wù)器寫入數(shù)據(jù)
connection.setDoInput(true); // 允許從服務(wù)器讀取數(shù)據(jù)
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();
// 處理響應(yīng)數(shù)據(jù)
inputStream.close();
}
connection.disconnect();
上述代碼示例了如何發(fā)送一個XML報文,并接收服務(wù)器的響應(yīng)。你可以根據(jù)實際情況修改其中的URL、XML內(nèi)容和請求頭等。