我有一个 solr 服务器,我在 web.xml 中使用摘要式身份验证来保护它,我需要从 java 调用 solr。 我今天阅读了大量主题并做了很多示例,但运气不佳。
我的 commons-httpclient 3.1 代码有效,我得到 200 OK。
URL url = new URL(solrUrl);
HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
httpClient.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_SCHEME),
new UsernamePasswordCredentials(user, password));
HttpMethod method = new GetMethod(solrUrl);
int responseCode = httpClient.executeMethod(method);
System.out.println(responseCode);
但是当我尝试使用 apache httpcomponent 4.2.2 执行此操作时,我总是得到 401 未授权。 这与官方示例几乎相同。
DefaultHttpClient httpclient = null;
try
{
URL url = new URL(solrUrl);
HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
httpclient = new DefaultHttpClient();
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(),targetHost.getPort()),
creds);
HttpGet httpget = new HttpGet(solrUrl);
HttpResponse response = httpclient.execute(targetHost,httpget);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine());
EntityUtils.consume(entity);
httpget.releaseConnection();
} catch (ClientProtocolException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
httpclient.getConnectionManager().shutdown();
}
我也尝试用 HttpUrlConnection 来做,并且总是得到相同的 401。
Authenticator authenticator = new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
PasswordAuthentication pa = new PasswordAuthentication(user, password.toCharArray());
System.out.println("calling solr with user:pass " + pa.getUserName() + ":******");
return pa;
}
};
Authenticator.setDefault(authenticator);
try
{
URL url = new URL(solrUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("type", "submit");
conn.setDoOutput(true);
conn.connect();
System.out.println( conn.getResponseCode());
conn.disconnect();
} catch (MalformedURLException mue)
{
mue.printStackTrace();
} catch (IOException ioe)
{
ioe.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
}
由于类路径问题,我想使用 apache httpcomponents 4,我正在放弃..
有什么帮助吗?
最佳答案
回答我自己: 显然我遇到了 jdk + tomcat 错误的组合:
jdk 1.6.0_45-b06 和 tomcat 7.0.34 出现,升级 tomcat 到 7.0.41 修复。
关于tomcat - apache httpcomponents 摘要认证失败,旧的 httpclient 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17395458/