I am doing a curl request :-
curl -X POST -H "Content-Type: application/json" -H "Accept: application/json,text/javascript" -d '[{"command": "system.login", "password": "guesswhatIam", "user": "theuser"}]' -k "https://TheIpAddress/ajax?sid="
The response I am getting from curl is :-
[{"status":"ok","sid":"7dfb39fd-2945-46d8-9036-81bb4ff2d858","deadtime":0}]
I'm trying to work out how to do the equivalent in Grails using HTTPBuilder, and I'd very much like to pull out that sid value.
I have tried this :-
def http = new HTTPBuilder ('https://' + ipAddress+'/ajax?sid=')
http.ignoreSSLIssues()
http.headers = [Accept: 'application/json,text/javascript', charset: 'UTF-8', ContentType: 'application/json' ]
http.request(POST) {
uri.path = ''
body = ['[{"command": "system.login", "password": "thepassword", "user": "theuser"}]']
requestContentType = ContentType.JSON
response.success = { resp,json ->
print "Success! ${resp.status}"
print json
}
response.failure = { resp ->
println "Request failed with status ${resp.status}"
}
}
I get a 200 success, but I cant seem to parse the data I get beck - I seem to get null?
Any pointers would be gratefully received.
So, in the end I gaveup with HTTPBuilder, and reverted to Java. This did the trick for me :-
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
URL url = new URL("http://" + ipAddress + "/ajax?sid=");
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Type", "application/json");
httpConn.setRequestProperty("Accept", "application/json,text/javascript");
httpConn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream());
writer.write("[{\"command\": \"system.login\", \"password\": \"thePassworrd\", \"user\": \"theUser\"}]");
writer.flush();
writer.close();
httpConn.getOutputStream().close();
InputStream responseStream = httpConn.getResponseCode() / 100 == 2
? httpConn.getInputStream()
: httpConn.getErrorStream();
Scanner s = new Scanner(responseStream).useDelimiter("\\A");
String response = s.hasNext() ? s.next() : "";
return response;
I hope this helps someone else with a similar problem.