【发布时间】:2013-06-28 01:00:44
【问题描述】:
我有一个通过 web.xml 中的摘要身份验证保护的 solr 服务器,我需要从 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,我正在放弃..
有什么帮助吗?
【问题讨论】:
标签: tomcat httpclient httpurlconnection digest-authentication apache-httpcomponents