gpt4 book ai didi

java - http 客户端 4.3 不发送凭据

转载 作者:行者123 更新时间:2023-11-29 05:29:26 24 4
gpt4 key购买 nike

我正在尝试使用 apache http 客户端 4.3 发送获取请求(发送到使用自签名证书的客户端),但是我每次都收到错误“需要身份验证”。在网络浏览器中,它工作得很好,所以用户名/密码/url 是正确的。这不是使用http client 4.3传递用户名/密码的方式吗?

public static String sendJsonHttpGetRequest(
String host,
String path,
String username,
String password,
int socketTimeout,
int connectionTimeout,
int connectionRequestTimeout
) throws Exception
{
String responseBody = null;
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustStrategy(){
@Override
public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType)
throws java.security.cert.CertificateException
{
return true;
}
});
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(credsProvider).build();
URIBuilder uriB = new URIBuilder().setScheme("https").setHost(host).setPath(path);
HttpGet _http = new HttpGet( uriB.build() );
RequestConfig _requestConfig = RequestConfig.custom().
setSocketTimeout(socketTimeout).
setConnectTimeout(connectionTimeout).
setConnectionRequestTimeout(connectionRequestTimeout).build();
_http.addHeader("Content-Type", "application/json");
_http.addHeader("Accept","application/json, text/xml;q=9, /;q=8");
_http.setConfig(_requestConfig);
// ###########################
ResponseHandler<String> response = new BasicResponseHandler();
responseBody = httpclient.execute(_http, response);
return responseBody;
}

最佳答案

事实证明现在使用 http 4+ 你必须在两个位置提供它才能工作,

第二个是

authCache.put(host, basicAuth);
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
HttpClientContext _context = HttpClientContext.create();
_context.setAuthCache(authCache);
_context.setCredentialsProvider(credentialsProvider);
responseBody = httpclient.execute(_http, response, _context);

关于java - http 客户端 4.3 不发送凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21647337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com