Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java run cURL and return website page results

Tags:

java

curl

I am trying to run some Java to run cURL to hit a website with data and this is working.

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("curl -s -S http://foo.com/testcode/Moo.cfm?PageName=" + $(Page.Name) + "&ProjectName=" + $(ProjectName));

cURL is hitting this website and sending the PageName and ProjectName variables.

The web page outputs some JSON.

How do i capture this JSON that the website is displaying and use it in my Java?

like image 435
Chad Gray Avatar asked May 31 '26 07:05

Chad Gray


1 Answers

You need to read the input stream from the process. Something like this should work using 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();

This will then print the full result in both cases

However, if you are looking for ways to just talking to websites you are probably better off using something like HttpClient or OKHttp.

If you are retrieving JSON I would suggest something like like Google GSON to parse it into objects. There is a good post on how to parse JSON at How to parse JSON in Java

like image 63
Asthor Avatar answered Jun 02 '26 19:06

Asthor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!