0

我有一个 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,我正在放弃..

有什么帮助吗?

4

1 回答 1

1

回答我自己:显然我遇到了 jdk + tomcat 错误的组合:

爪哇错误

Tomcat的错误

它发生在 jdk 1.6.0_45-b06 和 tomcat 7.0.34 上,将 tomcat 升级到 7.0.41 修复它。

于 2013-07-01T02:20:44.937 回答