简体   繁体   English

Groovy 用于 Script Runner 的 Rest/HTTP 请求本机

[英]Groovy Rest/HTTP Request Native for use with Script Runner

I am trying to build a simple Http Get request that requires me to submit an api key as authentication (api key as unsername and blank password).我正在尝试构建一个简单的 Http 获取请求,该请求要求我提交 api 密钥作为身份验证(api 密钥作为无用户名和空白密码)。 I have seen some solutions using the groovyx.net.http.HTTPBuilder library.我已经看到一些使用 groovyx.net.http.HTTPBuilder 库的解决方案。 However, the piece of code will need to be deployed in an evironment that does not allow for libraries.但是,这段代码需要部署在不允许库的环境中。 So I tried the following where is the url of the website i am trying to reach:所以我尝试了以下我要访问的网站的 url 在哪里:

// GET
def get = new URL("<url>").openConnection();
def getRC = get.getResponseCode();
println(getRC);
if(getRC.equals(200)) {
    println(get.getInputStream().getText());
}

As expected this returns error 400 since I do not include any authentication with the api key, so I tried the following where is the api key:正如预期的那样,这将返回错误 400,因为我没有使用 api 密钥进行任何身份验证,所以我尝试了以下 api 密钥在哪里:

def get = new URL("<url>");
def authString = "<api_key>:".getBytes().encodeBase64().toString();
def conn = get.openConnection();
conn.setRequestProperty("Authorization", "Basic ${authString}");
def getRC = conn.getResponseCode();
println(getRC);
println(conn.getInputStream().getText());

But I still get the 400 error.但我仍然收到 400 错误。 I tried picking up the request through Fiddler but it doesn't seem to be tracking it (executing Groovy code through GroovyConsole).我尝试通过 Fiddler 获取请求,但它似乎没有跟踪它(通过 GroovyConsole 执行 Groovy 代码)。

The second approach works.第二种方法有效。 My mistake was to not substitute spaces in the URL with % signs.我的错误是没有用 % 符号替换 URL 中的空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM