java - 如何在发布请求中设置身份验证?
问题描述
我有这个,从 xml (soap) 文件发出 post 请求的代码
public static SoapEnv doRequest(String url, String requestPath) throws IOException, InterruptedException {
String requestBody = inputStreamToString(new FileInputStream(new File(requestPath)));
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
XmlMapper xmlMapper = new XmlMapper();
SoapEnv value = xmlMapper.readValue(response.body(), SoapEnv.class);
return value;
}
它有效。
但现在我需要添加基本身份验证。我有登录名和密码。
如何以编程方式执行此操作?
解决方案
您只需要添加一个带有 Base64 编码的身份验证凭据的标头,并用冒号“:”分隔。
像这样的东西;
String auth = "username:password";
String base64Creds = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Authorization", "Basic " + base64Creds)
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
推荐阅读
- graphviz - Graphviz:如何为不同集群中的节点赋予相同的等级
- symfony - 为 Symfony Messenger 使用默认传输(跳过 amqp)
- jquery - 仅使用对象唯一值对数组项进行分组
- php - 如何使用按钮选择列表的最新或下一个元素
- excel - 我可以使用数组来使用 like 运算符比较多个条件吗?
- python - 如何“不要在 matplotlib 中拉伸轴”
- c++ - 将 std::vector 复制到 ac 样式数组中
- google-apps-script - 使用 Google Apps 脚本为单击按钮后显示的某些内容抓取网站
- sql - 表单的控件不会在 DataSet 更改时更新
- c - 如何在两条直线之间生成随机坐标?