Splunk Search

Getting Search Results using Java REST API

misteryuku
Communicator

Am i right to say that the results derived from the Splunk search is returned as XML by default?
I was using the Java Splunk REST API to get the results.

This is the code that i used :

InputStream dataStream = job.getResults();

Does this input stream data contain XML?

I attempted to output the data as XML file using Java but sometimes I can view the XML file and most of the time i ran the same Splunk search using Java and when i view the xml file on the browsers, I saw the message that says something like XML must have a top level element and sometimes there is a blank space on the browser and the windows notepad.

What is the cause of this problem? I need an answer urgently!!!!!

Tags (4)
0 Karma

harikag
New Member

@misteryuku & @psanford_splunk could you please help me in writing a java code to export search results in json format..i have tried the above method but still failing to get the result.

0 Karma

psanford_splunk
Splunk Employee
Splunk Employee

Hi - You can set the output_mode on your results to json, xml, csv. Take a look at this code that sets the output mode to JSON.

Job job = service.getJobs().create("search index=twitter | head 5");

    while (!job.isDone()) 
    {
           try
           {
                Thread.sleep(2000);
           }
           catch (InterruptedException e) {}

           job.refresh();
    }

    Map<String, Object> outputArgs = new HashMap<String, Object>();
    outputArgs.put("output_mode", "json");

    InputStream stream = job.getResults(outputArgs);

    InputStreamReader reader = new InputStreamReader(stream);
    OutputStreamWriter writer = new OutputStreamWriter(System.out);

    int size = 1024;
    char[] buffer = new char[size];

    try
    {

    while (true) {
        int count = reader.read(buffer);
        if (count == -1) break;
        writer.write(buffer, 0, count);
    }

    writer.write("\n");
    writer.close();
    reader.close();
    }
    catch (Exception e) {}

    job.cancel();
Get Updates on the Splunk Community!

Earn a $35 Gift Card for Answering our Splunk Admins & App Developer Survey

Survey for Splunk Admins and App Developers is open now! | Earn a $35 gift card!      Hello there,  Splunk ...

Continuing Innovation & New Integrations Unlock Full Stack Observability For Your ...

You’ve probably heard the latest about AppDynamics joining the Splunk Observability portfolio, deepening our ...

Monitoring Amazon Elastic Kubernetes Service (EKS)

As we’ve seen, integrating Kubernetes environments with Splunk Observability Cloud is a quick and easy way to ...