Home » Java » Convert Curl commands in java

Convert Curl commands in java

Posted by: admin August 11, 2018 Leave a comment

Questions:

I would like to ask you if someone can help to convert the following cURL commands in Java:

  1. curl -X POST --data '{"kind": "pyspark"}' -H "Content-Type: application/json" localhost:8998/sessions
  2. curl localhost:8998/sessions/0/statements -X POST -H 'Content-Type: application/json' -d '{"code":"2 + 2"}'

I tried with the following code but I got this error :
java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost:8998/sessions.

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
public class ApacheLivyBase {

    public int createSession(String urlString, String kind) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setUseCaches(false);
            conn.setAllowUserInteraction(true);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            OutputStream os = conn.getOutputStream();
            os.write(kind.getBytes("UTF-8"));
            os.close();
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            String result = IOUtils.toString(in, "UTF-8");
            System.out.println(result);
            System.out.println("result after Reading JSON Response");
            JSONObject myResponse = new JSONObject(result);
            System.out.println("result- " + myResponse.getString("result"));
            in.close();
            conn.disconnect();

        } catch (Exception e) {
            System.err.println(e);
        }
        return 0;
    }

    public static void main(String[] args) {
        String url = "http://localhost:8998/sessions";
        String data = "{\"data\": \"{\"kind\": \"spark\"}\"}";
        ApacheLivyBase  test =  new ApacheLivyBase();
        test.createSession(url, data);

    }

}

To be more specific, I am trying to send requests to apache livy REST API using Java.
Thank you very much for your help!

Answers: