EatingTooMuch EatingTooMuch - 2 months ago 11
Ajax Question

Converting curl command to Java or jQuery.ajax ()

I've never used

curl
before. I'm trying to run a command and parse the XML result in a web app.

curl -k https://ip.address.example --data-urlencode file.xml


So my options are limited to:


  • Execute the command using a servlet with
    Runtime.getRuntime.exec

  • Use
    jQuery.ajax()



I have tried this:

$.ajax({
url : "https://ip.address.example",
type : 'GET',
dataType : 'json',
contentType : 'application/json',
file: "file.xml",
success : function(data) {
console.log(JSON.stringify(data));
},
error : function() {
console.log("Cannot get data");
}
});


But it doesn't seem to work.

For the first method, I tried:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Gson gson = new GsonBuilder().serializeNulls().create();
Process p = Runtime.getRuntime().exec("curl -k https://ip.address.example --data-urlencode file.xml");
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line , output = "";
while ((line = reader.readLine()) != null) {
output += line + "\n";
}
System.out.println(output);
out.printf(gson.toJson(output));

} catch (Exception e) {
e.printStackTrace();

}
}


But i'm getting an error on
out.printf(gson.toJson(output));


java.util.UnknownFormatConversionException: Conversion = ')'


Any Suggestions?

Answer

The solution is : Replacing

out.printf(gson.toJson(output));

with out.printf(output);