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!

More Ways To Control Your Costs With Archived Metrics | Register for Tech Talk

Tuesday, May 14, 2024  |  11AM PT / 2PM ET Register to Attend Join us for this Tech Talk and learn how to ...

.conf24 | Personalize your .conf experience with Learning Paths!

Personalize your .conf24 Experience Learning paths allow you to level up your skill sets and dive deeper ...

Threat Hunting Unlocked: How to Uplevel Your Threat Hunting With the PEAK Framework ...

WATCH NOWAs AI starts tackling low level alerts, it's more critical than ever to uplevel your threat hunting ...