有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用SolrJ设置自定义请求头

我在Solr中配置了一个定制的http过滤器,它首先被调用(在org.apache.Solr.servlet.SolrDispatchFilter之前执行),用于每个到达Solr的请求。自定义筛选器在所有传入的solr请求中查找特定的请求头,只有当它存在时,才会将其发送给solr进行进一步处理

我使用SolrJ进行某些查询。在查询Solr到SolrJ时,有没有办法设置HTTP请求头

我的Solr和SorlJ版本是5.4.0


共 (2) 个答案

  1. # 1 楼答案

    对此解决方案有何想法

    // somewhere in my client initialization code
    HttpRequestInterceptor interceptor = (HttpRequest request, HttpContext context) -> {
            request.addHeader("myheadername", "myheadervalue");
    };
    
    HttpClientUtil.addRequestInterceptor(interceptor);
    HttpSolrClient solrClient = new HttpSolrClient.Builder(serverUrl).build();
    

    我的问题/担忧与HttpClientUtilhttps://solr.apache.org/docs/8_8_1/solr-solrj/org/apache/solr/client/solrj/impl/HttpClientUtil.html)中的这一评论有关

    This relies on the internal HttpClient implementation and is subject to change.

    WARNING: This API is experimental and might change in incompatible ways in the next release.

    我还对我创建的任何后续客户端实例的任何延迟影响有疑问/担忧。这些实例也会配置相同的拦截器吗?我能做些什么来确保他们不会

  2. # 2 楼答案

    您可以扩展HttpSolrClient创建自己的类MyHttpSolrClient,并自定义executeMethod添加自定义请求头的行为

    public class MyHttpSolrClient extends HttpSolrClient {
    
      public MyHttpSolrClient(String baseURL) {
        super(baseURL);
      }
    
      public MyHttpSolrClient(String baseURL, HttpClient client) {
        super(baseURL, client);
      }
    
      public MyHttpSolrClient(String baseURL, HttpClient client, ResponseParser parser) {
        super(baseURL, client, parser);
      }
    
      protected NamedList<Object> executeMethod(HttpRequestBase method, final ResponseParser processor) throws SolrServerException {
    
        // **Here you add your custom header**
        method.addHeader("Name", "Value");
    
        return super.executeMethod(method, processor);
      }
    }