首页 > 解决方案 > 如何在发布请求中设置身份验证?

问题描述

我有这个,从 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;
}

它有效。

但现在我需要添加基本身份验证。我有登录名和密码。

如何以编程方式执行此操作?

标签: javahttp

解决方案


您只需要添加一个带有 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();

推荐阅读