Grails httpbuilder json response - json

Having a few issues with the response handling of my httpbuilder post and json
within my service I have:
def jsonDataToPost = '{"accountNumber" : ' + accNo + ',"accountName" : ' + accName + '}'
def http = new HTTPBuilder('https://myurl.com/dataInput')
def jsonResponse
http.auth.basic ('username','password')
http.request(POST, ContentType.JSON) {
headers.'Content-Type' = 'application/json'
body = jsonDataToPost
response.success = { json ->
println("Success")
jsonResponse = json
}
response.failure = { json ->
println("Fail")
jsonResponse = json
}
}
firstly for some reason the code actually skips out rather than completing and so I'm not getting the jsonReponse I'm after but I can't figure out why? If I reponse my response.success/fail and I post correct data my json post works but again I still get no json back

Try this,
def requestData = [foo:bar]
http.request(POST, ContentType.JSON) {
headers.'Content-Type' = 'application/json'
body = (requestData as JSON).toString()
response.success = { resp, reader ->
println("Success")
jsonReponse = reader.text
}
response.failure = { resp, reader ->
println("Failed, status: " + resp.status)
jsonReponse = reader.text
}
}

If you're using Grails 3.x you can use http-builder-ng
https://http-builder-ng.github.io/http-builder-ng

Related

Get values from a JSON response in Groovy

I have a groovy script, it does an easy API call, and I am getting as response a JSON body.
How can I get, from the JSON body, a single value, and use it as a variable?
newRelease.request(GET) { req ->
requestContentType = ContentType.JSON
headers.'X-Octopus-ApiKey' = 'API-xxx'
response.success = { resp, JSON ->
return JSON
}
response.failure = { resp ->
return "Request failed with status ${resp.status}"
}
}
and this is the response
[DeploymentProcessId:deploymentprocess-Projects-370, LastReleaseVersion:null, NextVersionIncrement:0.0.41, VersioningPackageStepName:null, Packages:[], Links:[Self:/api/Spaces-1/deploymentprocesses/deploymentprocess-Projects-370/template]]
So what I am trying to extract is the NextVersionIncrement.
Any idea?

Kotlin-Volley Send JSON (post) with multiple json object in json array

i am build Point Of Sales apps and i can’t able to send multiple json object in json array. My apps read from android database (SQLite) and send multiple products to server. anyone help me ? thanks
Logcat : E/Volley: [893] BasicNetwork.performRequest: Unexpected response code 422 for https://…
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/x-www-form-urlencoded"
headers["Authorization"] = "Bearer " + user_info.token
return headers
}
override fun getParams(): MutableMap<String,String> {
val cartRepository = CartRespository(application)
val transaksi = cartRepository.getByIdTrans(id_trans)
val jo = JSONObject()
val ja = JSONArray()
for(i in 0 until transaksi.size){
ja.put(i,jo.put("product_id", transaksi[i].id_item))
ja.put(i,jo.put("jumlah", transaksi[i].kuantitas).toString())
}
val map = HashMap<String, String>()
map.put("rfid", "122312")
map.put("device", user_info.device)
map.put("products", ja.toString())
return map
}
this is my request API body, run normaly in postman.
{
"rfid": "122312",
"device": "1233311",
"products": [
{
"product_id": 4,
"jumlah": "1"
}
]
}

HTTPBuilder, returning JSON in not the correct format

I have a service that I am built\using returning data in the below format.
def responseData = [
'results': results,
'status': results ? "OK" : "Nothing present"
]
render(responseData as JSON)
The output looks like this, I have verified the output according to Fiddler
{"results":[{"class":"com.companyName.srm.ods.territory.Apo","id":2,"apoId":"5T9B0"}],"status":"OK"}
This is a simple POST call with a body of parameters from a search.
Using HTTPBuilder I get a different result
http.request(groovyx.net.http.Method.POST, groovyx.net.http.ContentType.URLENC) {req ->
uri.path = restUrl
body = requestData
response.success = {resp, json ->
println resp.statusLine.statusCode
println resp.statusLine
def slurper = new JsonSlurper()
String s = json.toString()
println s
returnJson = slurper.parseText(s)
}
response."422" = {resp, json ->
println ${resp.statusLine}
}
response.failure = {resp ->
println ${resp.statusLine}
}
}
["results":[{"class":"com.companyName.srm.ods.territory.Apo","id":2,"apoId":"5T9B0"}],"status":"OK":null]
This turns into a Mapped pair where the key is the JSON and the value is null, which is confusing as to why the HTTPBuilder is doing that.
In order to parse to JSON, I have to the following additional coding
s = s.replace(':null]', '')
s = s.replace('[', '')
This seems overly complicated for this type of implementation.
I have turned debug and nothing interesting is coming from that.
Any ideas
I use builder 0.7.1 and get json response the next way:
http.request(Method.POST, ContentType.TEXT) {
uri.path = pathToService
headers.'User' = user
headers.Accept = 'application/json'
body = requestBody //here I post some json
response.success = { resp, reader ->
//println reader.text;
println "response status: ${resp.statusLine}"
return = reader.text
}
response.failure = { resp, reader ->
println "Request failed with status ${resp.status}"
reader.responseData.results.each {
println " ${it.titleNoFormatting} : ${it.visibleUrl}"
}
}
}

Another issue when trying to POST JSON to REST URL via HttpBuilder

I read this and several other postings on SO and elsewhere about how to send a Post call via HttpBuilder with JSON as the data content. My problem is that NONE OF THOSE SOLUTIONS are working!
My problem is only slightly different. I have existing JSON data in a file. When I attempt to send this to the REST interface with curl:
curl -X POST -u "username:password" -d #/path/to/myFile.json http://localhost:8080/path/here --header "Content-Type:application/json"
all works perfectly well. Here is where I am at (some extra code IS in there, read on):
def myFile = new File('/path/to/myFile.json')
if (!myFile.exists()) println "ERROR! Do not have JSON file!"
def convertedText = myFile.text.replaceAll('\\{', '[')
convertedText = convertedText.replaceAll('\\}', ']')
def jsonBldr = new JsonBuilder()
jsonBldr myFile.text
println jsonBldr.toString()
def myClient = new groovyx.net.http.HTTPBuilder('http://username:password#localhost:8080/my/path')
myClient.setHeaders(Accept: 'application/json')
results = myClient.request(POST, JSON) { req ->
body = [ jsonBldr.toString() ]
requestContentType = JSON
response.success = { resp, reader ->
println "SUCCESS! ${resp.statusLine}"
}
response.failure = { resp ->
println "FAILURE! ${resp.properties}"
}
}
This results in the 'failure' closure with this data:
statusLine:HTTP/1.1 400 Exception evaluating property 'id' for java.util.ArrayList, Reason: groovy.lang.MissingPropertyException: No such property: id for class: java.lang.String
FWIW, there is no "id" in my JSON anywhere. If I change the "body" line from "[ jsonBldr.toString() ]" to "[ convertedText ]" - which is why that code is up there, I get the same error. If I take out the brackets on the body, I get an error stating that the body is not data for an array (as its a Map).
Can anyone (far groovier than I) tell me what the %%$## I am doing wrong???
You need JsonSlurper instead of JsonBuilder. After which the implementation would look like:
def myFile = new File('/path/to/myFile.json')
if (!myFile.exists()) println "ERROR! Do not have JSON file!"
def bodyMap = new JsonSlurper().parseText(myFile.text)
def myClient = new groovyx.net.http.HTTPBuilder('http://username:password#localhost:8080/my/path')
modelClient.setHeaders(Accept: 'application/json')
results = myClient.request(POST, JSON) { req ->
requestContentType = JSON
body = bodyMap
response.success = { resp, reader ->
println "SUCCESS! ${resp.statusLine}"
}
response.failure = { resp ->
println "FAILURE! ${resp.properties}"
}
}
However, I am not clear what is difference between myFile and modelFile in your code.

Get html body from response in groovy

I'm trying to see if a specific string exists in an html page but I can't seem to find an easy way to get the string that represents the body.
I've attempted:
http.request(Method.GET, { req ->
uri.path = '/x/app/main'
response.success = { resp, reader ->
assert resp.status == 200
println reader.text.startsWith('denied')
}
response.failure = { resp ->
fail("Failure reported: ${resp.statusLine}")
}
})
but reader.text is a NodeChildren object.
How do I get the html (or more specifically, the contexts of the body) as a string?
You can get an input stream directly off of the response. Try this:
http.request(Method.GET, { req ->
uri.path = '/x/app/main'
response.success = { resp ->
assert resp.status == 200
println resp.entity.content.text.startsWith('denied')
}
response.failure = { resp ->
fail("Failure reported: ${resp.statusLine}")
}
})