Question

I am using this code for POSTing JSON objeect to the URL groovy:

def http = new HTTPBuilder( 'myURL' )

// perform a POST request, expecting JSON response data
http.request( POST, JSON ) {
uri.path = myPath
uri.query = [ service_key:'1.0', event_type: 'trigger' ]
headers.'Content-Type' = 'application/json'

// response handler for a success response code:
response.success = { resp, json ->
println resp.status

// parse the JSON response object:
 json.responseData.results.each {
 ret = json.getText()
 println 'Response data: -----'
 println ret
 println '--------------------'
}
}

// handler for any failure status code:
response.failure = { resp ->
println "Unexpected error: ${resp.status} : ${resp.statusLine.reasonPhrase}"
}
}

  Ajax Code that works:(EDITED)
 $.ajax({       url:'https://events.pagerduty.com/generic/2010-04-15/create_event.json',                                                                       
            type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({

              service_key: "1379ca7018e94343bf5fa5add9fa42eb",
                 incident_key: "srv01/HTTP",
                event_type: "trigger",
                description: "TEst Test"
     }),
     dataType:'json'
     });
     alert('Message Sent');

Everytime I get Unexpected error:400:Bad Request, Same thing if I do it with $.ajax() it works. I get HTTP:200 OK on the response.What is going wrong here?

Thank You.

Was it helpful?

Solution

In the ajax example you are passing 4 elements as a JSON body, which will end up like this:

{"service_key": "1379ca7018e94343bf5fa5add9fa42eb",
 "incident_key": "srv01/HTTP",
 "event_type": "trigger",
 "description": "TEst Test"}

But in the groovy example you are only passing two query string params (which will be passed on the uri).

You should probably replace

uri.query = [ service_key:'1.0', event_type: 'trigger' ]

with:

body =  [service_key:'1.0', incident_key: "srv01/HTTP", event_type: 'trigger' description: "TEst Test"]

You should also output the response data in your failure response handlers as many services will give you a description of why you are not meeting the service contract.

OTHER TIPS

If you have access to the server that you're requesting data from, you should look at the log files.

A bad request generally means that the webserver doesn't like your URL, Query String or your HTTP headers. If you can get into the server you might be able to get more details.

Otherwise, is there a way you can log your request object before performing the HTTP post?

Also -- double check that your JSON data is properly formatted. In some frameworks I need to escape my JSON before sending it in a request object. Try logging that as well and looking to see if your framework requires you to process (or maybe even parse the data into a dictionary/associative array type structure).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top