如何在java上正确编写restheart的POST请求

时间:2018-03-08 09:36:27

标签: java http post restheart

我正在使用restheart为mongodb提供一个安静的界面。 Get方法运行良好,我从数据库中获取数据。但在这种情况下,我试图实现POST请求以在base中写入数据。我正在运行以下代码,但我收到了代码415不支持的媒体类型的响应。我的测试基础db1有一个集合testcoll,我试图用字段编写一个文档" name"和"评级"

 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());

    }
}

有什么问题,我该如何解决?

1 个答案:

答案 0 :(得分:0)

添加一行:

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

并编写字符串:

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

解决了我的问题。