Spring Boot Callable - 401 未经授权:[无正文]

问题描述 投票:0回答:1

我在发送身份验证请求的 Spring Boot 应用程序中使用 Callable 接口:

public class TestCallable implements Callable<TestDto> {

    TestEntity testEntity;

    public TestCallable(TestEntity testEntity) {
        this.testEntity = testEntity;
    }


    @Override
    public TestDto call() throws Exception {
        String authRequestBody = "{" +
                                    "\"username\": \"" + testEntity.getLogin() + "\"," +
                                    "\"password\": \"" + testEntity.getPassword() + "\"," +
                                    "\"client_id\": \"" + testEntity.getClientId() + "\"," +
                                    "\"client_secret\": \"" + testEntity.getClientSecret() + "\"" +
                                 "}";
        HttpHeaders authHeaders = new HttpHeaders();
        authHeaders.setContentType(MediaType.APPLICATION_JSON);
        authHeaders.set("Accept", "application/json");
        authHeaders.set("Grant_type", "password");
        HttpEntity<String> authEntity = new HttpEntity<String>(authRequestBody, authHeaders);
        RestTemplate restTemplate = new RestTemplate();
        TestDto testDto = testDto  = restTemplate.postForObject(testEntity.getEndpoint(), authEntity, TestDto.class);

        return testDto;
    }
}

我在 4 个线程中发送这些请求:

List<Future<TestDto>>  futuresList = new ArrayList<Future<TestDto>>();
ExecutorService pool = Executors.newFixedThreadPool(4);
for (Integer i=0; i<4; i++) {
    Callable<TestDto> callable = new TestCallable(testEntity);
    Future<TestDto> future = pool.submit(callable);
    futuresList.add(future);
}

问题是有时我会收到错误“401 Unauthorized: [no body]”。例如,我可以从 4 个可调用作业接收 4 个令牌 5 次,并在第 6 次尝试时收到错误。

如果我将线程数更改为 2,那么出现错误的频率就会减少。每次有 10 个线程失败。

它在 Postman 中总是运行良好。

如何了解问题的原因?

java spring-boot resttemplate callable
1个回答
0
投票

改变

authHeaders.set("Grant_type", "password");

authHeaders.set("Authorization", "password");
© www.soinside.com 2019 - 2024. All rights reserved.