java http发送xml报文
时间: 2023-10-16 13:07:04 浏览: 82
您可以使用Java中的HttpURLConnection类来发送HTTP请求并发送XML报文。以下是一个简单的示例代码:
```java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpXmlSender {
public static void main(String[] args) throws Exception {
// 设置请求的URL
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 设置请求头的Content-Type为text/xml
connection.setRequestProperty("Content-Type", "text/xml");
// 启用输出流,用于发送XML报文
connection.setDoOutput(true);
// 构造XML报文
String xmlData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><data>...</data></root>";
// 发送XML报文
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(xmlData);
outputStream.flush();
outputStream.close();
// 获取响应结果
int responseCode = connection.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 打印响应结果
System.out.println("Response Code: " + responseCode);
System.out.println("Response Body: " + response.toString());
}
}
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)