在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內容和請求頭等。