Search code examples
springapigrailsgroovyhttpbuilder

Vertical response api in grails


I'm trying to use Vertical response api in my grails project. But it giving following error

CODE:

def http = new HTTPBuilder()

http.request('https://vrapi.verticalresponse.com/',GET, TEXT) { req ->
    uri.path =  'api/v1/contacts?type=basic'
    headers.'Authorization' = 'Bearer api_token'
    headers.'Content-Type'='application/json'


    print('====================================')
    response.success = { resp, reader ->
        assert resp.status == 200
        println "My response handler got response: ${resp.statusLine}"
        println "Response length: ${resp.headers.'Content-Length'}"
        reader // print response reader
    }

    // called only for a 404 (not found) status code:
    response.'404' = { resp ->
        println 'Not found'
    }
}

ERROR:

Unauthorized. Stacktrace follows:
groovyx.net.http.HttpResponseException: Unauthorized
    at groovyx.net.http.HTTPBuilder.defaultFailureHandler(HTTPBuilder.java:652)
    at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:508)
    at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:441)
    at groovyx.net.http.HTTPBuilder.request(HTTPBuilder.java:417)
    ...

Solution

  • After using HttpClient instead of HTTPBuilder it working without any problem. So I think the problem is with HTTPBuilder

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet('http://vrapi.verticalresponse.com/api/v1/contacts?type=basic');
    
    // add request header
    request.addHeader("Authorization","Bearer token")
    
    HttpResponse response = client.execute(request);
    
    print("Response Code : "
            + response.getStatusLine().getStatusCode())
    
    BufferedReader rd = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent()));
    
    
    render rd.readLines()