我正在做一个curl请求:-
curl -X POST -H“内容类型:application/json”-H“接受:application/json,文本/javascript”-d'[{“command”:“system.login”,“password”:“guesswhatIam ", "user": "theuser"}]' -k "https://TheIpAddress/ajax?sid="
我从curl得到的回应是:-
[{“状态”:“确定”,“sid”:“7dfb39fd-2945-46d8-9036-81bb4ff2d858”,“死区时间”:0}]
我正在尝试找出如何使用 HTTPBuilder 在 Grails 中执行等效操作,并且我非常想提取该 sid 值。
我已经尝试过这个:-
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}"
}
}
我获得了 200 成功,但我似乎无法解析我得到的数据 - 我似乎得到了 null?
如有任何指点,我们将不胜感激。
所以,最终我放弃了 HTTPBuilder,转而使用 Java。这对我有用:-
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;
我希望这可以帮助其他有类似问题的人。