-2

We have an application with API via HTTP. If I want to get data from this API from linux script I just run something like

curl -s http://10.20.1.116:8080/afa/report?session=fd58603c6673

and get back json

{
  "content" : [ {
    "id" : 6243,
    "user" : "admin",
    "firewall" : "NewGroup_Lab",
    "updateDate" : 1406225284152,
    "attributes" : {
      "EmailNotification" : "True",
      "Job_status" : "COMPLETED",
      "Submitted_by" : "afa",
      "Regulatory_score_glba_group" : "22,9,10,65",
      "Pid" : "11254",
      "Owner" : "admin",
      "Regulatory_score_nist_800-41_group" : "15,13,8,52",
    }

Now we want to use this API in java program. What is the correct way to access the API URL? What should I replace the curl with?

Thanks.

user4157124
  • 2,452
  • 12
  • 22
  • 36
Alex
  • 33
  • 1
  • 7
  • possible duplicate of [How to send HTTP request in java?](http://stackoverflow.com/questions/1359689/how-to-send-http-request-in-java) – Jake Cobb Jul 24 '14 at 19:15

2 Answers2

0

You'll want to look into either the built-in HttpURLConnection class in Java or the Apache HttpComponents library which has a nicer API.

HttpURLConnection is very verbose.

Your example with Apache HttpComponents:

String json = Request.Get("http://10.20.1.116:8080/afa/report?session=fd58603c6673")
    .connectTimeout(1000)
    .socketTimeout(1000)
    .execute()
    .returnContent()
    .asString();

Look here for a great answer of how to use HttpURLConnection. Here is an example of the HttpClient API in Apache HttpComponents.

Community
  • 1
  • 1
Raman Lalia
  • 245
  • 1
  • 5
-1
URL url = new URL("your_url");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str;
// read a line
while ((str = in.readLine()) != null) {
     //write to file, concatenate to string, etc
}
mistahenry
  • 8,064
  • 3
  • 22
  • 36