java http认证账号密码发送xml报文
时间: 2023-10-16 16:08:00 浏览: 124
在Java中发送带有HTTP认证的XML报文,你可以使用Java的URLConnection类来完成。以下是一个示例代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
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 HttpXmlRequest {
public static void main(String[] args) {
String username = "username";
String password = "password";
String xmlPayload = "<xml>...</xml>";
String url = "http://example.com/api";
try {
// 创建URL对象
URL apiUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
// 设置HTTP请求方法为POST
connection.setRequestMethod("POST");
// 设置HTTP Basic认证
String auth = username + ":" + password;
byte[] authBytes = auth.getBytes(StandardCharsets.UTF_8);
String encodedAuth = Base64.getEncoder().encodeToString(authBytes);
connection.setRequestProperty("Authorization", "Basic " + encodedAuth);
// 设置请求头和请求体
connection.setRequestProperty("Content-Type", "application/xml");
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(xmlPayload.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 Body: " + response.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文