【问题标题】:How to set Content-Length in a put request with Groovy HttpBuilder如何使用 Groovy HttpBuilder 在 put 请求中设置 Content-Length
【发布时间】:2016-04-12 21:11:08
【问题描述】:

我正在尝试在 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
    }

【问题讨论】:

    标签: groovy github-api httpbuilder


    【解决方案1】:
    1. 为避免 NPE,您需要在 HTTPBuilder 中指定默认 URI 构造函数或提供 URI 作为request 方法的参数。
    2. 无需显式指定Content-Length 标头,过多会导致异常。 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 
        ...
    

    【讨论】:

    • 感谢您的帮助,我刚刚发布了我的 getHTTPBuilder() 函数。 baseUrl 是 GitHub REST API 的默认 URI。
    【解决方案2】:

    抱歉,我认为 baseUrl 为空。

    【讨论】:

      猜你喜欢
      • 2012-01-05
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      • 2019-11-21
      • 2011-08-04
      • 2012-01-22
      • 2019-10-06
      相关资源
      最近更新 更多