Jirong Hu
Jirong Hu

Reputation: 2375

How to set Content-Length in a put request with Groovy HttpBuilder

I am trying to use HttpBuilder in Groovy to suspend a GitHub user, but got a null pointer error at the last line. The REST API is defined here: 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
    }

Upvotes: 0

Views: 1480

Answers (2)

Jirong Hu
Jirong Hu

Reputation: 2375

Sorry, I figured the baseUrl is null.

Upvotes: 0

Evgeny
Evgeny

Reputation: 2568

  1. To avoid NPE you need to specify default URI in HTTPBuilder constructor or provide URI as a parameter of request method.
  2. There is no need to specify Content-Length header explicitly, more over it will cause exception. Content-Length is automatically calculated and in your case it is 0 as you don't specify request body.

Try following

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 
    ...

Upvotes: 1

Related Questions