-->

Headers in POST in Grails 3 app are not being sent

2019-09-13 02:08发布

问题:

Using Grails 3.0.9, and grabbing the freshest REST API with this snippet in gradle.build:

compile 'org.grails:grails-datastore-rest-client:4.0.7.RELEASE', {
    ['commons-codec', 'grails-async', 'grails-core',
     'grails-plugin-converters', 'grails-web', 'groovy'].each {
        exclude module: it
    }
}

I am trying to make the following POST request:

def rest = new RestBuilder(headers:["X-LSS-Env":"devmo"], connectTimeout:10000, readTimeout:20000)
response = rest.post("http://..../..") {
    accept "application/json"
    contentType "application/json"
    json jsonBuilder
}

Now, the POST receiver gets the json okay, give back a response okay, but this is the problem: it receives the headers as an empty map or as null!

So, what is the correct way of passing header data to the POST receiver? This is needed because the environment key X-LSS-Env could have different values, which instructs the receiver to do further routing based on it. Same with the GET request of course.

* UPDATE *

The consumer of my POST requests is actually a Java application, running on Apache Tomcat/8.0.26. The is how the service looks on the other side:

private javax.servlet.http.HttpServletRequest hsr;
@POST
@Path("/na")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response postSomething(Ggfp ggfp ){
    try {
        Enumeration<String> hnames = hsr.getHeaderNames();
        int i = 0;
        while (hnames.hasMoreElements()) {
            String headerName = hnames.nextElement();

            System.out.println(++i+ " headerName: " + headerName);
            String val = hsr.getHeader(headerName);
            System.out.println("         val: " + val);
        }
        String hval = hsr.getHeader("X-LSS-Env");
        return Response.status(Status.OK).entity("X-LSS-Env is " + hval).build();
    } catch (Exception e) {
    }
}

Calling this service from Postman works, headers are identified. Calling it from the Grails app results into an empty map - like I am sending no headers!

回答1:

The RestBuilder constructor never liked the way I used (or abused) it. Here is a clean way of achieving what I set out to do, with tryCatch logic if a timeout transpires.

def makePostWsr(serviceUrl, jsonBuilder) {
  try {
     def rest = new RestBuilder(connectTimeout:connectTimeout, readTimeout:readTimeout)
     def response = rest.post("$wsUrl/$serviceUrl") {
        header 'X-LSS-Env', 'devmo'
        accept "application/json"
        contentType "application/json"
        json jsonBuilder
     }
     response
  } catch (Exception e) {
     println "== problem makePostWsr on $serviceUrl"
     null
  }
}