如何在发布请求中设置身份验证?

时间:2019-12-10 13:07:31

标签: java http

我有这个代码,它从xml(soap)文件中发出发布请求

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;
}

它有效。

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

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

1 个答案:

答案 0 :(得分:2)

您只需要添加带有以冒号“:”分隔的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();