Solr 4 with basic authentication

前端 未结 3 1235
野趣味
野趣味 2021-01-20 08:27

I am trying to connect to solr using solrj. My solr instance runs in jetty and is protected with basic authentication. I found these links that contain relevant information.

3条回答
  •  [愿得一人]
    2021-01-20 08:46

    i had the same problem when implementing partial documents update. i solved the problem by implementing PreemptiveAuthInterceptor. see below code

    PoolingClientConnectionManager cxMgr = new PoolingClientConnectionManager(
                            SchemeRegistryFactory.createDefault());
                    cxMgr.setMaxTotal(100);
                    cxMgr.setDefaultMaxPerRoute(20);
    
                    DefaultHttpClient httpclient = new DefaultHttpClient(cxMgr);
                    httpclient.addRequestInterceptor(
                            new PreemptiveAuthInterceptor(), 0);
                    httpclient.getCredentialsProvider().setCredentials(
                            AuthScope.ANY,
                            new UsernamePasswordCredentials(solrDto.getUsername(),
                                    solrDto.getPassword()));
    
                    HttpSolrServer solrServerInstance = new HttpSolrServer(solrDto.getUrl(),
                            httpclient);
                    solrServerInstance.setRequestWriter(new BinaryRequestWriter());
                    solrServerInstance.setAllowCompression(true);
    

    You also need:

        private class PreemptiveAuthInterceptor implements HttpRequestInterceptor {
    
                public void process(final HttpRequest request, final HttpContext context)
                        throws HttpException, IOException {
                    AuthState authState = (AuthState) context
                            .getAttribute(ClientContext.TARGET_AUTH_STATE);
    
                    // If no auth scheme avaialble yet, try to initialize it
                    // preemptively
                    if (authState.getAuthScheme() == null) {
                        CredentialsProvider credsProvider = (CredentialsProvider) context
                                .getAttribute(ClientContext.CREDS_PROVIDER);
                        HttpHost targetHost = (HttpHost) context
                                .getAttribute(ExecutionContext.HTTP_TARGET_HOST);
                        Credentials creds = credsProvider.getCredentials(new AuthScope(
                                targetHost.getHostName(), targetHost.getPort()));
                        if (creds == null)
                            throw new HttpException(
                                    "No credentials for preemptive authentication");
                        authState.setAuthScheme(new BasicScheme());
                        authState.setCredentials(creds);
                    }
    
                }
    
            }
    

提交回复
热议问题