konsul777
konsul777

Reputation: 21

How to correctly write POST request for a restheart on java

I am using restheart to provide a restful interface to mongodb. Get method is working good, I'm getting data from database in respons. But in this instance I'm trying to implementing POST request to write data in base. I'm running following code but I'm getting response with code 415 unsupported media type. My test base db1 have one collection testcoll where I'm trying to write a document with fields "name" and "rating"

 public class PostMethodJava {
 public static void main(String[] args) throws IOException {
    URL url;
    try {
        url = new URL("http://127.0.0.1:8080/db1/testcoll/");
        //url = new URL("http://google.com/");
    } catch (Exception et) {
        System.out.println("Data URL is broken");
        return;
    }

    HttpURLConnection hc = null;

    try {
        hc = (HttpURLConnection) url.openConnection();

        String login = "admin:12345678";
        final byte[] authBytes = login.getBytes(StandardCharsets.UTF_8);

        final String encoded = Base64.getEncoder().encodeToString(authBytes);
        hc.addRequestProperty("Authorization", "Basic " + encoded);

        System.out.println("Authorization: " + hc.getRequestProperty("Authorization"));

        //hc.setDoInput(true);
        hc.setDoOutput(true); //<== removed, otherwise 415 unsupported media type
        hc.setUseCaches(false);

        hc.setRequestMethod("POST");
        //hc.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
        hc.setRequestProperty("Accept", "application/json");
    } catch (Exception et) {
        System.out.println("Can't prepare http URL con");
    }

    System.out.println(hc.toString());

    String parameter = "mame=test1&rating=temp";
    int plength = parameter.length();
    byte[] pdata = parameter.getBytes(StandardCharsets.UTF_8);
    try (DataOutputStream out = new DataOutputStream(hc.getOutputStream())){
        out.write(pdata);
    }

    int rc = hc.getResponseCode();

    System.out.println("response code: " + rc);
    System.out.println("response message: " + hc.getResponseMessage());

    }
}

What is wrong and how can I fix it?

Upvotes: 0

Views: 754

Answers (1)

konsul777
konsul777

Reputation: 21

Adding a line:

hc.setRequestProperty("Content-Type","application/json");

and writing the string:

String parameter = "{\"name\":\"doubleabc\",\"rating\":\"allright\"}";

fixed my problem.

Upvotes: 1

Related Questions