如何使用 Groovy HttpBuilder 在放置请求中设置内容长度

How to set Content-Length in a put request with Groovy 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[=11=].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
    }
  1. 为避免 NPE,您需要在 HTTPBuilder 中指定默认 URI 构造函数或提供 URI 作为 request 方法的参数。
  2. 不需要明确指定Content-Length header,超过它会导致异常。 Content-Length 是自动计算的,在您的情况下是 0,因为您没有指定请求正文。

尝试关注

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

def httpBuilder = getHTTPBuilder()

//path as a parameter of request
httpBuilder.request(path, Method.PUT, ContentType.TEXT) { req ->
    uri.path = '/suspended'
    //no need to specify 
    //headers.'Content-Length' = 0 
    ...

抱歉,我认为 baseUrl 为空。