我已经开始使用Lucidworks Fusion (2.1.2),并且最习惯使用Groovy。附注: python 'requests‘无缝地处理了这个问题,但我很固执,不想使用python……
Fusion有很有前途的API,我期待着在Groovy中使用它。
我尝试了几种方法(最终找到了几种有效的方法)。我欢迎关于为什么基本的RESTClient不适合我的反馈,以及其他“简单”的解决方案。
这是我尝试过的:
groovyx.net.http.HTTPBuilder hb = new HTTPBuilder(FUSION_API_BASE)
hb.auth.basic(user, pass)由于401未授权而失败(我相信是因为编码的原因)。HTTPBuilder来自gradle:
compile 'org.codehaus.groovy.modules.http-builder:http-builder:0.7.1'我也试过了:
HttpPost httpPost = new HttpPost(url);
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "sean"));
nvps.add(new BasicNameValuePair("password", "mypass"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response2 = httpclient.execute(httpPost);并得到了:
{"code":"unauthorized"}还尝试了:
String path = '/api/apollo/introspect'
URL url = new URL('http', 'corp', 8764, path)
try {
def foo = url.getContent()
log.info "Foo: $foo"
} catch (IOException ioe){
log.warn "IO ERR: $ioe"
}它抛出了(现在预期的) IOError: 401。如果有人想知道更多关于我的失败的信息,请让我知道,我可能会用大量的技术细节让你感到厌烦。
我正在厚颜无耻地回答我自己的问题(如下所示),但希望一些时髦的老师能给我一点启发。
发布于 2016-04-03 10:38:34
所以我问了这个问题,并发布了我找到的解决方案。希望人们能添加更好的解决方案,甚至可以解释我在最初的尝试中遗漏了什么。
这是我的首选解决方案(下面的三个解决方案都来自谷歌,但我丢失了链接,请随时戳我,我会把它们挖出来--对原创海报的赞誉):
String furl = "${FUSION_API_BASE}${path}" //http://localhost:8764/api/apollo/introspect
RESTClient rc = new RESTClient(furl)
rc.headers['Authorization'] = 'Basic ' + "$user:$pass".bytes.encodeBase64()
//rc.headers['Authorization'] = 'Basic ' + "$user:$pass".getBytes('iso-8859-1').encodeBase64()
def foo = rc.get([:])
log.info "Foo: $foo"和另一个可行的解决方案:
RESTClient rest = new RESTClient( 'http://localhost:8764/' )
HttpClient client = rest.client
client.addRequestInterceptor(new HttpRequestInterceptor() {
void process(HttpRequest httpRequest, HttpContext httpContext) {
httpRequest.addHeader('Authorization', 'Basic ' + 'sean:mypass'.bytes.encodeBase64().toString())
}
})
def resp = rest.get( path : path)
assert resp.status == 200 // HTTP response code; 404 means not found, etc.
println resp.getData()对于那些在家里记分的人,可以用python解决方案进行比较:
import requests
from requests.auth import HTTPBasicAuth
rsp = requests.get('http://corp:8764/api/apollo/introspect', auth=HTTPBasicAuth('sean', 'lucid4pass'))
print "Response ok/status code: %s/%s", rsp.ok, rsp.status_code
print "Response content: %s", rsp.contentHTH,
肖恩
https://stackoverflow.com/questions/36381045
复制相似问题