如何使用Groovy HttpBuilder在put请求中设置Content-Length

时间:2016-04-12 21:11:09

标签: groovy github-api httpbuilder

我试图在Groovy中使用HttpBuilder来挂起GitHub用户,但在最后一行得到了一个空指针错误。 REST API在此处定义:https://developer.github.com/v3/users/administration/

String path = "http://github.mycompany.com/api/v3/users/$username/suspended"        
print "path: $path \n"
log.info("Suspend GitHub users")

def httpBuilder = getHTTPBuilder()
httpBuilder.request(Method.PUT, ContentType.TEXT) { req ->
    uri.path = path
    headers.'Content-Length' = 0


path: http://github.mycompany.com/api/v3/users/jasionb/suspended 
16:59:46.467 [main] INFO  c.o.devops.tools.GitHubUserManager - Suspend GitHub users
16:59:46.898 [main] ERROR c.o.devops.tools.GitHubUserManager - GithubUserManager FAILED
java.lang.NullPointerException: null
    at groovyx.net.http.HTTPBuilder.request(HTTPBuilder.java:383) ~[http-builder-0.7.1.jar:na]
    at groovyx.net.http.HTTPBuilder$request$0.call(Unknown Source) ~[na:na]
    at com.otpp.devops.tools.GitHubUserManager.suspendUsers(GitHubUserManager.groovy:105) ~[GitHubUserManager.groovy:na]
    at com.otpp.devops.tools.GitHubUserManager$suspendUsers.call(Unknown Source) ~[na:na]
    at com.otpp.devops.tools.GitHubUserManager.main(GitHubUserManager.groovy:150) ~[GitHubUserManager.groovy:na]



baseUrl='http://github.otpp.com/api/v3'

HTTPBuilder getHTTPBuilder() {
        def httpBuilder = new HTTPBuilder(baseUrl)
        httpBuilder.ignoreSSLIssues()

        httpBuilder.client.addRequestInterceptor(new HttpRequestInterceptor() {
            void process(HttpRequest httpRequest, HttpContext httpContext) {
                httpRequest.addHeader('Authorization', 'Basic ' + "$user:$password".bytes.encodeBase64().toString())
            }
        })          

        return httpBuilder
    }

2 个答案:

答案 0 :(得分:1)

  1. 要避免NPE,您需要在lastwarn中指定默认URI 构造函数或提供URI作为warnlist=[]; while somecondition % Code that might generate a warning, eg your 'quadprog' function call. warnlist = [warnlist; lastwarn] warning('') % Clear the last warning, so you wont get dupes in the list end 方法的参数。
  2. 无需明确指定HTTPBuilder标头,更多会导致异常。 request会自动计算出来,在您的情况下会Content-Length,因为您没有指定请求正文。
  3. 尝试以下

    Content-Length

答案 1 :(得分:0)

抱歉,我认为baseUrl为空。