Guide on incorporating curl in Java and extracting JSON feedback

Is it possible to use a curl command that provides a JSON response in Java and parse the JSON response using Java?

Here is an example of Java code attempting to achieve this:

public static void main(String[] args) throws Throwable {

    try {
        InputStream stream = Runtime.getRuntime().exec("curl --globoff --insecure --silent -u username:password -X GET -H 'Content-Type: application/json' \"http://ficcjira.xyz.com/rest/api/2/search?jql=project=ABC&fields=Timetracking\"").getInputStream();

        BufferedReader input = new BufferedReader(new InputStreamReader(stream), 1);

        input.readLine();
        input.read();
        input.read();

        DataReader reader = new JsonReader(input)
                .addField("TimeSpent", "//array/object/timespent")
                .addRecordBreak("//array/object");

        /*reader = new TransformingReader(reader)
                .add(new BasicFieldTransformer("TimeSpent").stringToDouble());*/

        DataWriter writer = new StreamWriter(System.out);

        JobTemplate.DEFAULT.transfer(reader, writer);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

However, the following error is encountered:

Cannot run program "curl": CreateProcess error=2, The system cannot find the file specified

Answer №1

        Runtime rt = Runtime.getRuntime();
        Process p1;
        Process p2;
        try {
            String postSubmissionJSon = "{"data":"value"}";

            String[] stringPost = {"curl", "-X", "POST", "https://your-url.com/api/posts",
                "--cert", "test.crt.pem",
                "--key", "test.key.pem",
                "-H", "accept: application/json",
                "-H", "content-type: application/json",
                "-d", postSubmissionJSon};

            ProcessBuilder ps = new ProcessBuilder(stringPost);
            //ps.redirectErrorStream(true);
            Process pr = ps.start();
            pr.waitFor();

            BufferedReader reader2 = new BufferedReader(new InputStreamReader(pr.getInputStream()));

            String line2 = "";
            while ((line2 = reader2.readLine()) != null) {
                output.append(line2 + "\n");
            }

            System.out.println("\n\n\noutput====" + output + "===\n\n\n");

            String sbToString = output.toString();

            JSONObject jSONObject = new JSONObject(sbToString);

            System.out.println(jSONObject.toString());

            p1 = Runtime.getRuntime().exec("pwd");
            p1.waitFor();
            BufferedReader reader1a
                    = new BufferedReader(new InputStreamReader(p1.getInputStream()));

            String line1a = "";
            while ((line1a = reader1a.readLine()) != null) {
                output.append(line1a + "\n");
                System.out.println("output====" + output + "===");
            }
        } catch (Exception e) {
            System.out.println("===============ERROR===============\n" + e.getMessage() + "\n\n\n");
        }

/*NOTE : Your Key (test.key.pem) and Cert (test.crt.pem) should be located on your proper directory. For glassfish it is on "~/glassfish4/glassfish/domains/domain1/config" or your can specify exact location by changing "--cert", "test.crt.pem" --> "/home/user/files/test.crt.pem". Same with the key. */

Answer №2

If you're looking to access the Jira Rest API, there are several options available to you. It's important to choose the method that best fits your needs and technical capabilities.

  1. One option is to use the Rest Java Client for Java. You can find more information about this client here.

If you prefer using Jersey, it allows you to call the REST APIs and read the responses effectively. Alternatively, if you're working with Spring, the RestTemplate is a convenient tool. You can check out some sample code here.

  1. There are other options available such as Restlet and Apache commons. It's essential to explore and determine which one suits your project requirements best.

Using the curl option is recommended only when calling from a bash script. If you decide to go this route, consider utilizing jq for parsing the response data. More information on jq can be found here.

Answer №3

My response will address the error that was brought to your attention. To resolve this issue, it is essential to have cUrl installed and ensure that it has been added to your PATH variable.

You can verify this by attempting to execute the curl command from your Windows command prompt. If you do not receive a valid response, it indicates that cUrl may not be installed or included in your PATH variable.

To install cUrl, you can visit , download the necessary files, extract them, add cUrl to your PATH variable, and then try running the cUrl command once more.

Answer №4

To retrieve and parse JSON data from a stream, you can utilize a tool like Gson in your Java application:

try (
    Reader reader = new InputStreamReader(
        Runtime.getRuntime().exec("curl -h").getInputStream()
    )
) {
    JsonElement element = new JsonParser().parse(reader);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Swift HTTP request is missing any post data

When attempting to send post data via http to the server, it seems that no post data is being returned. Below is a snippet of the code I used: var request = URLRequest(url: URL(string: "http://posttestserver.com/post.php")!) request.httpMethod = "POST" re ...

Can TestNG allow for the implementation of global parameters?

Currently in the process of automating a web app using Selenium WebDriver framework along with TestNG. Looking to assign parameters for each test classes in the testing.xml file, however most resources online only show how to set predefined parameters for ...

Having difficulty in closing the chat box that has been opened in a web application

I attempted to close the chat box by targeting the element in this manner: driver.findElement(By.cssSelector("span.icon")).click(); However, it is throwing an exception stating "Element is not currently visible and so may not be interacted with" htt ...

Navigating through Leaflet to reference a .json file

Looking to integrate a .json vector layer into a Leaflet.js map, which can be seen on the GitHub page here, with the source code available here. Here's a condensed version of the file for reference (full version visible on the linked GitHub page). & ...

Issue with array merging/inserting feature not functioning as expected

Here are two arrays that I have: First Array: "workingHours": [ { "opening": "09:30", "closing": "13:30", "dayName": "sunday" }, { ...

Struggling with understanding how to parse JSON in VB.net

Looking for some assistance. I'm grappling with parsing the JSON output provided by the cloudstack API in vb.net and feeling a bit stuck. The JSON response from the cloudstack looks like this: { "listcapacityresponse": { "count": 6, ...

Converting a Map to Json in Play Scala: A Step-by-Step Guide

Is there a way to convert the given Map structure, which is of type Map[String,Any], into JSON in Scala using Play framework? val result = s .groupBy(_.dashboardId) .map( each => Map( "dashboardId" -> each._1, "cubeId" -> ...

Error: Unable to retrieve data through Ajax request

$(document).ready(function(){ /* Fetching Data from TTC for Union Station */ $.getJSON("http://myttc.ca/Union_station.json?callback=?", function(data){ if (routes.length > 0) { // Display the stop details with departur ...

Chrome PWA debugger fails to respond when attempting to use the "add to homescreen" button

I have been endeavoring to implement the "add to Homescreen" prompt feature on my website. After thoroughly reviewing Google developer documentation, I have successfully configured everything accordingly. However, when I try to manually add my page to the ...

Understanding JSON Parsing in Jade

I am facing a challenge with handling a large array of objects that I am passing through express into a Jade template. The structure of the data looks similar to this: [{ big object }, { big object }, { big object }, ...] To pass it into the Jade templat ...

Totally clueless when it comes to JSON

After diving into tutorials on JSON, the structure and syntax are finally clicking for me. However, I'm currently working on a project that requires a GET, and it seems like JSON could help with this. I've come across comparisons of JSON and AJA ...

Locate a specific data point within an array of JSON objects

After receiving an array of JSON objects from JSP, I now have a set of data that contains book titles. "Titles":[ { "Book3" : "BULLETIN 3" } , { "Book1" : "BULLETIN 1" } , { "Book2" : "B ...

What is the best way to iterate over JSON data and organize the output based on the key value?

Let's say I want to filter through the JSON data below and only push the home_team_conference if it matches Southeastern. My goal is to organize the data by home_team_conference in order to display each array on different pages of my website. Currentl ...

Angular's GET request response is returning an "Undefined" value instead of the

As an Angular beginner, I've successfully set up and tested a service that retrieves data from a JSON file using the Get method. However, when attempting to access the data inside the JSON file, it returns as undefined. My goal is to use this data as ...

Utilizing a JSON object to send data to a C# WebAPI POST endpoint that accepts a parameter of a generic abstract class

I have a generic abstract class that defines the structure of an object to be POSTed to this endpoint. The class is as follows, with an example implementation: public abstract class Animal<T> { public string Name { get; set; } pu ...

How to designate the specific container to be updated in the XMLHTTP JSON code within a Joomla website?

Below are some functions that were created by a former developer who is no longer with the company. These functions query a database and return JSON code to update the inner HTML of a specific div. I have now been tasked with setting up a typeahead search ...

Creating an if-else statement in PHP based on a JSON response - what's the best way to

I have made a JSON request that checks if my PC has a proxy set up. If it does, it shows "Yes", otherwise it shows "No". Now, I would like to publish two statements: If the status is "Yes": I want to display "You are protected" in green. If the status ...

Registering your phone with Gigya

Currently, I am utilizing Gigya as the single sign-on system for my iOS application. It has been successfully integrated, allowing users to log in using their Twitter, Facebook accounts, or through manual email registration. However, due to the limitation ...

Using Python for Web Scraping and Converting JSON Data to CSV

My journey: I am just beginning with Python and have no prior experience as a developer. My objective: I aim to scrape the Sofascore API in order to retrieve Soccer Lineups and convert them into CSV format. The JSON data needs to be manipulated to extract ...

The function echo json_encode($row) is outputting repetitive values

Here is my PHP code: $result = mysql_query("SELECT * FROM backup WHERE owner='$email'") or die(mysql_error()); $dataCount = mysql_num_rows($result); $row = mysql_fetch_array($result); echo json_encode($row); And this is the result it returns: ...