java http发送xml报文加上账号密码认证
时间: 2023-10-16 07:08:00 浏览: 121
要在Java中使用HTTP发送XML报文并加上账号密码认证,可以使用Java的HttpURLConnection类。下面是一个示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class HttpXmlRequestExample {
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");
// 设置HTTP基本认证
String username = "yourUsername";
String password = "yourPassword";
String auth = username + ":" + password;
String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
String authHeader = "Basic " + encodedAuth;
connection.setRequestProperty("Authorization", authHeader);
// 设置请求的Content-Type为application/xml
connection.setRequestProperty("Content-Type", "application/xml");
// 启用输出流,以便发送XML数据
connection.setDoOutput(true);
// 构建XML报文
String xmlData = "<xml>...</xml>";
// 将XML报文写入输出流
try (OutputStream outputStream = connection.getOutputStream()) {
byte[] input = xmlData.getBytes(StandardCharsets.UTF_8);
outputStream.write(input, 0, input.length);
}
// 获取响应结果
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
System.out.println(response.toString());
}
} else {
System.out.println("HTTP request failed with response code: " + responseCode);
}
// 关闭连接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文