Search code examples
javaresthttporientdb

Why my Java project can't do a succesfully POST method for connect with my OrientDB?


I have a DB and need to do a REAL POST. I did a good GET and POST is failed (I don't know where) and don't have problem in compilation.

The POST method failed:

URL url = new URL(urlPost);
HttpURLConnection conexionPost = (HttpURLConnection) url.openConnection();

conexionPost.setDoOutput(true);
conexionPost.setRequestMethod("POST");
conexionPost.setRequestProperty("Accept-Encoding", "gzip,deflate");
conexionPost.setRequestProperty("Content-Length", "216");
conexionPost.connect();
conexionPost.disconnect();

And the GET method that is ok:

  String sGet = "xxxxx:2480/query/mydb/sql/...";
    URL urlGet = new URL(sGet);
    HttpURLConnection conexionGet = (HttpURLConnection) urlGet.openConnection();
    conexionGet.setDoInput(true);
conexionGet.setRequestMethod("GET");

    BufferedReader in1 = new BufferedReader(new InputStreamReader(conexionGet.getInputStream()));
    String texto = "";
    String request = "";
    while ((texto = in1.readLine()) != null) {
        request += texto;
    }
    in1.close();
    System.out.println(request);

My code SQL for create vertex is something like this:

String urlPost = urlServer + "/command/mydb/sql/CREATE%20VERTEX%20V%20"
+ "SET%20certificateFingerprint%20=%20%27" + datos[9]+ "%27";

The answer of DB is: {"result":[]} and my DB is empty (obviously).

Thank in advance.


Solution

  • You are missing authentication in your POST request.

    I've tried with this code and it works great:

    
    
        import java.io.IOException;
        import java.net.HttpURLConnection;
        import java.net.URL;
    
        import org.apache.commons.codec.binary.Base64;
    
    
        public class Stack38089384 {
    
            public static void main(String[] args) throws IOException {
                String urlPost = "http://localhost:2480/command/Stack38089384/sql/create%20class%20Test%20extends%20v";
                URL url = new URL(urlPost);
                HttpURLConnection conexionPost = (HttpURLConnection)url.openConnection();
    
                String userCredentials = "root:root";
                String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
                conexionPost.setRequestProperty ("Authorization", basicAuth);
                conexionPost.setRequestMethod("POST");
                conexionPost.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conexionPost.setRequestProperty("Content-Language", "en-US");
                conexionPost.setUseCaches(false);
                conexionPost.setDoInput(true);
                conexionPost.setDoOutput(true);
    
                System.out.println(conexionPost.getResponseCode());
            }
    
    
        }
    
    

    Hope it helps.