java 休息请求期间偶尔出现“407 Proxy Authentication required”错误

Dee*_*ass 1 java rest spring web-services jakarta-ee

我正在尝试对我的客户端 URL 之一执行 REST 请求,以使用代理获取响应。大多数时候,我能够使用我的代码获取响应。但有时,当我尝试使用我的代码发送请求时,我会收到“407 需要代理身份验证”错误。这种情况很少发生,但一旦我收到此错误,对于每个连续的请求,我都会收到相同的错误。但是当我使用 chrome 中的 POSTMAN 工具将生成的相同请求发送到同一 URL 时,我会得到响应。但是,一旦我收到邮递员的响应,如果我再次尝试使用我的代码,我不仅会从本地计算机上收到响应,还会从运行代码的不同计算机上收到响应。我非常高兴对这个问题感到困惑,无法弄清楚为什么会出现这种奇怪的情况。我的代码中是否缺少某些内容。请帮助我。我在下面给出了我的代码:

代码

public Map<String ,Object> ConnectRestService(MyRequest myRequest, String postURL, String httpProxy,int timeout int httpPort, Map<String ,Object> responseMap)
        throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CustomException{

    MyResponse myResponse = new MyResponse();
    Map<String ,Object> responseReturnMap = new HashMap<>();
    String output = "";
    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {

        @Override
        public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
            // TODO Auto-generated method stub
            return true;
        }
    };

    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(null, acceptingTrustStrategy)
            .build();


    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
    HttpClient httpClient;
    httpClient = HttpClients.custom().setSSLSocketFactory(csf).setProxy(new HttpHost(httpProxy, httpPort)).build();

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("Content-type", "text/xml");
    httpHeaders.add("Accept", "text/xml");
    httpHeaders.add("access-control-allow-origin", "*");
    httpHeaders.add("content-encoding", "UTF-8");
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    requestFactory.setConnectTimeout(timeout);


    try {
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        HttpEntity<MyRequest> entity = new org.springframework.http.HttpEntity<MyRequest>(
                myRequest, httpHeaders);
        ResponseEntity<String> response = restTemplate.exchange(postURL, HttpMethod.POST, entity, String.class);


    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }

    return responseReturnMap;
}
Run Code Online (Sandbox Code Playgroud)

请帮助我弄清楚我在这里缺少什么。

Pra*_*ore 5

如果出现407错误,您收到的响应必须包含特殊Proxy-Authenticate标头。该标头将告诉您代理服务器期望哪种身份验证。

您需要做的就是Proxy-Authorization在请求中包含标头。代理授权标头的典型语法是Proxy-Authorization:<type-of-authentication-scheme> <credentials-for-authentication-at-proxy-server>

Proxy-Authenticate标头会让您知道需要使用的身份验证方案的类型。