我有一个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因为类路径问题,我正在放弃..
任何帮助?
答案 0 :(得分:1)
回答我的自我: 显然我已经遇到了jdk + tomcat错误的组合:
它发生在jdk 1.6.0_45-b06和tomcat 7.0.34,将tomcat升级到7.0.41修复它。