java 不适用URL对象http发送xml报文
时间: 2024-02-05 07:04:07 浏览: 99
Java使用URL对象发送HTTP请求是完全可行的,包括发送XML报文。以下是一个使用URL对象发送XML报文的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpClient {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://example.com/api");
// 创建HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 设置请求头部信息
connection.setRequestProperty("Content-Type", "application/xml");
// 启用输出流,用于发送请求数据
connection.setDoOutput(true);
// 创建XML报文
String xmlData = "<xml>...</xml>";
// 获取输出流并写入XML报文
OutputStream outputStream = connection.getOutputStream();
outputStream.write(xmlData.getBytes());
outputStream.flush();
outputStream.close();
// 获取响应码
int responseCode = connection.getResponseCode();
// 读取响应数据
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出响应结果
System.out.println("Response Code: " + responseCode);
System.out.println("Response Data: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文