java - java rest请求期间偶尔出现“407 Proxy Authentication Required”错误
问题描述
我正在尝试对我的一个客户端 URL 执行 REST 请求以使用代理获取响应。大多数情况下,我能够使用我的代码获取响应。但有时当我尝试使用我的代码发送请求时,我是收到“需要 407 代理身份验证”错误。这种情况很少发生,但是一旦我收到此错误,对于每个连续的请求,我都会收到相同的错误。但是当我使用 chrome 的 POSTMAN 工具将生成的相同请求发送到相同的 URL 时,我会得到响应。但是,一旦我得到 POSTMAN 的响应,如果我再次尝试使用我的代码,我不仅会从本地机器上得到响应,还会从运行代码的不同机器上得到响应。我非常对这个问题感到困惑,无法弄清楚为什么会发生这种奇怪的情况。我的代码中是否缺少某些东西。请帮帮我。我在下面给出了我的代码:
代码
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;
}
请帮我弄清楚我在这里缺少什么。
解决方案
如果出现407
错误,您收到的响应必须包含一个特殊的Proxy-Authenticate
标头。此标头将告诉您代理服务器期望的身份验证类型。
您需要做的是Proxy-Authorization
在您的请求中包含一个标头。Proxy-Authorization 标头的典型语法是Proxy-Authorization:<type-of-authentication-scheme> <credentials-for-authentication-at-proxy-server>
.
Proxy-Authenticate
标头会让您知道您需要使用的身份验证方案的类型。
推荐阅读
- javascript - 无法将状态从父组件传递给子组件(番茄钟状态计数器)
- scala - Spark 2.0 - 将数据帧拆分为子数据帧而不使用 createOrReplaceTempView
- c# - 如何通过单击桌面上的文件来启动我的程序并读取文本文件
- docusignapi - 当某些收件人已经签名时,有没有办法更新复合模板以添加文档
- python - Python循环列出打印索引或数组
- translation - 翻译在我的 symfony 应用程序中不起作用
- php - 使用 WooCommerce api 添加变体
- php - 逐行比较大型Mysql表(1列)与文件
- flutter - 如何测试断言?
- python - Python,Selenium,等待元素的文本改变