我正在尝试运行一些Java来运行cURL来访问一个包含数据的网站,这是有效的。
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("curl -s -S http://foo.com/testcode/Moo.cfm?PageName=" + $(Page.Name) + "&ProjectName=" + $(ProjectName));
cURL正在访问此网站并发送PageName和ProjectName变量。
网页输出一些JSON。
如何捕获网站正在显示的JSON并在我的Java中使用它?
答案 0 :(得分:1)
您需要从流程中读取输入流。这样的东西应该可以使用Java 8
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("curl -s -S http://foo.com/testcode/Moo.cfm?PageName=" + $(Page.Name) + "&ProjectName=" + $(ProjectName));
//Java 8 version
String result = new BufferedReader(
new InputStreamReader(pr.getInputStream()))
.lines()
.collect(Collectors.joining("\n"));
//Older version than java 8
BufferedReader response = new BufferedReader(new InputStreamReader(pr.getInputStream()));
StringBuilder result = new StringBuilder();
String s;
while((s = response.readLine()) != null) {
result.append(s);
}
System.out.println(result.toString());
//You then need to close the BufferedReader if not using Java 8
response.close();
这将在两种情况下打印完整结果
但是,如果您正在寻找与网站交谈的方法,那么您可能最好使用HttpClient或OKHttp。
如果您正在检索JSON,我建议像Google GSON一样将其解析为对象。关于如何在How to parse JSON in Java
解析JSON的帖子很好答案 1 :(得分:0)
我想我会将其作为答案发布,但这会输出网站返回的第一行文字。现在我需要学习如何解析JSON。我是一个Java新手...感谢大家的帮助!
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("curl -s -S
Process pr = rt.exec("curl -s -S http://foo.com/testcode/Moo.cfm?PageName=" + $(Page.Name) + "&ProjectName=" + $(ProjectName));
BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String response;
response = br.readLine();
System.out.println(response);