java http加上账号密码发送xml报文
时间: 2023-10-16 21:07:04 浏览: 101
在Java中,你可以使用HttpURLConnection类来发送HTTP请求,并且可以附加账号密码进行身份验证。以下是一个示例代码,展示如何使用Java的HttpURLConnection类发送XML报文并附加账号密码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
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 HttpXmlSender {
public static void main(String[] args) {
// 设置账号密码
String username = "your_username";
String password = "your_password";
// 构建XML报文
String xml = "<xml>...</xml>";
// 设置请求地址
String url = "http://example.com/api";
try {
// 创建URL对象
URL apiUrl = new URL(url);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
// 设置请求方法
connection.setRequestMethod("POST");
// 添加账号密码的身份验证
String authString = username + ":" + password;
String encodedAuthString = Base64.getEncoder().encodeToString(authString.getBytes(StandardCharsets.UTF_8));
String authHeader = "Basic " + encodedAuthString;
connection.setRequestProperty("Authorization", authHeader);
// 设置请求头部属性
connection.setRequestProperty("Content-Type", "application/xml");
// 允许输出数据
connection.setDoOutput(true);
// 发送请求数据
OutputStream outputStream = connection.getOutputStream();
outputStream.write(xml.getBytes(StandardCharsets.UTF_8));
outputStream.flush();
outputStream.close();
// 获取响应
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应数据
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
inputStream.close();
// 处理响应数据
System.out.println("Response: " + response.toString());
}
// 断开连接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文