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!

Introducing the 2024 SplunkTrust!

Hello, Splunk Community! We are beyond thrilled to announce our newest group of SplunkTrust members!  The ...

Introducing the 2024 Splunk MVPs!

We are excited to announce the 2024 cohort of the Splunk MVP program. Splunk MVPs are passionate members of ...

Splunk Custom Visualizations App End of Life

The Splunk Custom Visualizations apps End of Life for SimpleXML will reach end of support on Dec 21, 2024, ...