背景:Elasticsearch 7.9.0 開啟了用戶名密碼校驗(yàn),需要使用用戶名密碼登入。并且設(shè)置的user、role等權(quán)限。那么之前直接訪問的方式是不行的。需要使用認(rèn)證的方式進(jìn)行訪問。直接上最終能成功的Clientnt代碼:

image.png
最關(guān)鍵的是builder.setDefaulHeaders(new BasicHeader[]{ new BasicHeader("Authorization","Basic "+auth) })
這行代碼,需要設(shè)置一下請(qǐng)求header,不然會(huì)報(bào)錯(cuò):
{ "error": { "root_cause": [ { "type": "security_exception", "reason": "missing authentication credentials for REST request [/bank/_search]", "header": { "WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\"" } } ], "type": "security_exception", "reason": "missing authentication credentials for REST request [/bank/_search]", "header": { "WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\"" } }, "status": 401 }